Python3爬虫简易实例1(Requests正则)
来源:互联网 发布:富国优化增强债券c 编辑:程序博客网 时间:2024/05/22 20:45
抓取某电影网TOP100
1.分析源码,以便于写正则表达式
这里是网页关键部分的源码:
然后针对它写正则表达式:
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a' + '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>' + '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S)
然后完善:
必须模拟User-Agent的信息,Python默认的信息是python,必须把它改成浏览器的信息,否则会出错。import requestsfrom requests.exceptions import RequestExceptionimport reimport jsondef get_one_page(url, headers): try: response = requests.get(url, headers=headers) if response.status_code == 200: return response.text else: return None except RequestException: return Nonedef parse_one_page(html): pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a' + '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>' + '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S) items = re.findall(pattern, html) 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) + "\n")def main(offset): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36" } url = "http://maoyan.com/board/4?offset=" + str(offset) html = get_one_page(url, headers) for item in parse_one_page(html): write_to_file(item)if __name__ == '__main__': for i in range(10): main(i*10)
写入异常处理防止出错。
存取下来的文本内容:
还可以完善一下它,加入进程池,加速爬取。
from multiprocessing import Pool'''.................'''if __name__ == '__main__': pool = Pool() pool.map(main, [i*10 for i in range(10)])
阅读全文
0 0
- Python3爬虫简易实例1(Requests正则)
- python3爬虫初探(二)之requests
- python3爬虫初探(八)requests
- python3的爬虫抓取猫眼电影的信息(requests+正则表达式)
- Python3爬虫学习笔记(3.正则详解及实例)
- python3实现爬虫爬取今日头条上面的图片(requests+正则表达式+beautifulSoup+Ajax+多线程)
- Python requests爬虫实例
- python3爬虫攻略(9):requests的使用
- python3爬虫(一)requests库的学习
- python3 爬虫入门(二)requests库基本使用
- python3爬虫——正则表达式re详解(1)
- Python3:网络爬虫(1)
- python3爬虫超简单实例
- python3 [爬虫实战] selenium + requests 爬取安居客
- python3 [爬虫实战] selenium + requests 爬取安居客
- Python3网络爬虫:requests爬取动态网页内容
- python3爬虫requests.get(url)出现http 500错误
- Python3爬虫学习笔记(2.Requests库详解)
- PowerDesigner提示Existence of index、key、reference错误
- java jdbc connect
- 阿里云配置mysql并使用navicat连接
- 程序员必读书籍及导读指南
- 6.接口、对象、比较、构造器、方法
- Python3爬虫简易实例1(Requests正则)
- Linux基础知识(一)
- 1.html及css
- Disruptor入门
- 小学奥数思维训练题(十七)
- 51nod1649-二维最短路|(补图&最短路)-齐头并进
- base64转成图片的方法
- super关键字
- Java接口