赞
踩
只是记录一下自己的学习过程。
学习爬虫需要对网页的组成有一定了解。可以去网络上搜索学习一下,不需要对整个html语言有较深认知。
使用爬虫不能爬取有版权或者付费的内容,大多数情况下只是为了快速获取,结合数据分析得到比较直观的规律。
有一定基础的同学简单看一下代码就好了。别的其实都是废话。
示例源码1:
import re import urllib.request import requests url='https://www.qqtn.com/article/article_32160_1.html' headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.26'} page_text=requests.get(url=url,headers=headers) page_text.encoding=page_text.apparent_encoding print(page_text) print(page_text.text) filter='<img src="(.*?)"' image_url=re.findall(filter,page_text.text) print(image_url) path='C:\\Users\\asus\\Desktop\\spider_image' for index,ima in enumerate(image_url): imag=requests.get(ima) with open(path+'\\'+str(index)+'ima.png','wb+') as f: f.write(imag.content)
示例代码2:
import re import requests url='http://www.imeitou.com/nvsheng/233342.html' headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.26'} pageopen=requests.get(url=url,headers=headers) pageopen.encoding=pageopen.apparent_encoding filter='<img src="(.*?)"' image_url=re.findall(filter,pageopen.text) path='C:\\Users\\asus\\Desktop\\ima' for index,ima in enumerate(image_url): imag=requests.get(ima) with open(path+'\\'+str(index)+'ima.png','wb+') as f: f.write(imag.content)
1.获取URL和headers
获取headers:F12->网络->ctrl+r->第一个->滑到最下面->user_Agent。
2.获取网页内容。
(1)使用urllib模块:
import urllib.request.urlopen
with urlopen(url) as fp:
page_text=fp.read().decode()
(2)import request
page_text=request.get()
page_text.encoding=page_text.apparent_encoding
print(page_text.text)
request模块简介:
3.通过re.findall(pattern,page_text.text)方法筛选获取网页文本得到图片地址。
两种方式:
(1)通过正则表达式:re.findall(pattern,page_text)
(2)xpath
4.通过request.get(image_url)获取图片的二进制内容。
5.新建文件夹并下载图片。
(1)建立文件夹:if not os.path.exists('D:\\')
os.mkdir('D:\\')
(2)创建文件:with open方法创建
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。