Python爬虫总结

时间:2023-03-09 05:18:58
Python爬虫总结

Python爬虫的原理:1通过URLopen()来获取到url页面, 这个过程可以加代理

         2这个页面上都是字符串,所以我们而通过字符串查找的方法来获取到目标字符串,用到了正则来匹配目标re.findall(pattern,string)

          或者 查找页面的字符串,bs4.Beautifulsoup(html)可以将url页面的标签提取出来,提升查找效率

         3.目标字符串为网址:urlretrieve()   或者写到excel中

代理访问:

 url='http://www.baidu.com'
iplist=['121.226.174.246:8080','210.38.1.142:8080','210.38.1.143:8080']
proxyhandler=urllib.request.ProxyHandler({'http':random.choice(iplist)})
openner=urllib.request.build_opener(proxyhandler)
openner.addheaders=[('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) '
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0')]
urllib.request.install_opener(openner) response=urllib.request.urlopen(url)
html=response.read().decode('utf-8')

beautifulsoup 来把所有的标签都列出来,然后通过标签的属性来找出每个标签下的url

 url="https://tieba.baidu.com/p/1988291937?fr=ala0&pstaala=1&tpl=5&isgod=0"
html=urllib.request.urlopen(url)
bsobj=bs4.BeautifulSoup(html) #beautifulsoup直接定位标签
print(type(bsobj))
imglist=bsobj.findAll("img",{"src":re.compile(".*\.jpg")}) #imglist是含有所有标签类型的元素 img是一个标签 src是标签的属性
for img in imglist:
print(img["src"])

对图片进行下载

 def get_img(html):
p=r'<img class="BDE_Image" src="([^"]+\.jpg)"'
imglist=re.findall(p,html)
# for each in imglist:
# print(each)
for each in imglist:
filename=each.split("/")[-1]
urllib.request.urlretrieve(each,filename,None)