python使用正则抓取数据
今天主要学习了python使用正则抓取网页数据。
首先这是正则的几个步骤:
1、用import re 导入正则表达式模块;
2、用re.compile()函数创建一个Regex对象;
3、用Regex对象的search()或findall()方法,传入想要查找的字符串,返回一个Match对象;
4、调用Match对象的group()方法,返回匹配到的字符串
import requests from requests.exceptions import RequestException import re import json from multiprocessing import Pool # 获取单个页面 def get_one_page(url): try: # 添加头部信息 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.162 Safari/537.36' } response = requests.get(url, headers=headers) # 进行状态码判断,是否正确读取到网页 if response.status_code == 200: return response.text return None except RequestException: return None # 解析网页 def parse_one_page(html): pattern = re.compile('<dd>.*?board-index.*?>(d+)</i>.*?src="(.*?)".*?name"><a' +'.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>' +'.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S) items = re.findall(pattern, html) # print(items) for item in items: yield { 'index': item[0], 'image': item[1], 'title': item[2], 'actor': item[3].strip()[3:], 'time': item[4].strip()[5:], 'score': item[5] + item[6] } # 将抓取的内容保存到文件 def write_to_file(content): with open('result.txt', 'a', encoding='utf-8') as f: f.write(json.dumps(content, ensure_ascii=False) + ' ') f.close() def main(offset): url = 'http://maoyan.com/board/4?offset=' + str(offset) html = get_one_page(url) # print(html) # parse_one_page(html) for item in parse_one_page(html): print(item) write_to_file(item) if __name__ == '__main__': pool = Pool() pool.map(main, [i*10 for i in range(10)]) # for i in range(10): # main(i*10)
代码和数据转载自CSDN:https://blog.csdn.net/whjkm/article/details/80846544