Python爬虫总结

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

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

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

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

代理访问:

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

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

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

对图片进行下载

1 def get_img(html):
2     p=r'<img class="BDE_Image" src="([^"]+.jpg)"'
3     imglist=re.findall(p,html)
4     # for each in imglist:
5     #     print(each)
6     for each in imglist:
7         filename=each.split("/")[-1]
8         urllib.request.urlretrieve(each,filename,None)
原文地址:https://www.cnblogs.com/caojunjie/p/6727536.html