python3.8爬虫_python爬虫系列(3.8-正则的使用)
一、需要系統的學習正則表達式
1、元字符
1..:除了\n以外的任意字符
2.*:出現0到多次
3.?:出現0或者1次
4.+:表示出現1到多次
2、常用的方法
1.compile:表示生成正則表達式參考地址
2.findall:查找全部注意返回的是一個列表參考地址
import re
import requests
class GuShiWen(object):
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36',
}
def get_html(self):
"""
抓取古詩文第一頁內容
:return:
"""
response = requests.get(url=self.url, headers=self.headers)
if response.status_code == 200:
gusiwen_list = []
params = re.compile('.*?(
', re.S)article_list = params.findall(response.text)
for article in article_list:
gusiwen_dict = {}
title = re.compile('.*?(.*)', re.S).findall(article)[0]
content = re.compile('.*?
(.*?)', re.S).findall(article)[0].strip().replace('', '')
gusiwen_dict['title'] = title
gusiwen_dict['content'] = content
gusiwen_list.append(gusiwen_dict)
print(gusiwen_list)
return
print('請求錯誤')
if __name__ == "__main__":
gusiwen = GuShiWen()
gusiwen.get_html()
1、基本上是使用findall方法
2、主要是網頁多行字符要使用re.S
3、如果正則比較復雜的時候使用re.compile()對正則包裝下
總結
以上是生活随笔為你收集整理的python3.8爬虫_python爬虫系列(3.8-正则的使用)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab时域转换成频域_从时域到频域
- 下一篇: 电脑向linux服务器传输文件,wind