【Python】爬虫小结

本文总结了Python爬虫的相关知识,包括获取http和https页面源代码,抓取带JS的页面信息,如何截取所需内容,以及应对IP被封的策略。详细介绍了使用User-Agent伪装、设置代理IP、解析json和html内容的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.获取页面源代码


1.1获取http类型的页面源代码

  1. import time,os,cookielib,urllib2,urllib  
  2. import datetime,StringIO,gzip  
  3.   
  4. def getHtml(url,referurl=None,cookie=None,postdata=None,ip=None):  
  5.     cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())#伪装cookies  
  6.     if ip:  
  7.         proxy_support = urllib2.ProxyHandler({'http':ip})#代理  
  8.         opener = urllib2.build_opener(proxy_support, cookie_support, urllib2.HTTPHandler)  
  9.         urllib2.install_opener(opener)  
  10.     else:  
  11.         opener = urllib2.build_opener( cookie_support, urllib2.HTTPHandler)  
  12.         urllib2.install_opener(opener)  
  13.     headers = {'User-Agent''Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0'}#伪装浏览器  
  14.     req = urllib2.Request(url,headers = headers)  
  15.     if referurl:  
  16.         req.add_header('referer',referurl)  
  17.     if cookie:  
  18.         req.add_header('Cookie', cookie)  
  19.     if postdata:  
  20.         try:  
  21.             req.add_data(urllib.urlencode(postdata))  
  22.         except:  
  23.             req.add_data(postdata)  
  24.     content=urllib2.urlopen(req,timeout=120).read()  
  25.     try:  
  26.         gzp_content = StringIO.StringIO(content)  
  27.         gzipper = gzip.GzipFile(fileobj =gzp_content)  
  28.         content =gzipper.read()  
  29.     except:  
  30.         1  
  31.     return content  

1.2获取https类型的页面源代码

  1. import pycurl,StringIO  
  2.   
  3. def getHtml(url):  
  4.     c=pycurl.Curl()  
  5.     c.setopt(c.URL, url)  
  6.     b = StringIO.StringIO()  
  7.     c.setopt(c.WRITEFUNCTION, b.write)  
  8.     c.setopt(c.COOKIEFILE, '')  
  9.     c.setopt(pycurl.USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)")  
  10.     c.setopt(c.HTTPHEADER, ['Accept: text/html''Accept-Charset: UTF-8'])  
  11.     c.setopt(c.SSL_VERIFYPEER, 0)  
  12.     c.setopt(c.SSL_VERIFYHOST, 0)  
  13.     c.setopt(c.FOLLOWLOCATION, 1)  
  14.     c.setopt(c.HEADER,False)  
  15.     c.perform()  
  16.     html=b.getvalue()  
  17.     b.close()  
  18.     c.close()  
  19.     return html  



2.抓取带JS的页面信息(下拉加载,点击加载等)


2.1用firebug中的XHR分析出所需内容真正的url,再用该url请求需要的内容

2.2对应的url有的很长,可以试着不断裁短,只要内容不变就好


3.截取需要的内容


3.1若返回的是json格式的内容,可以用json.loads(html)将内容转成字典来操作并截取内容

3.2若返回的内容是html格式的内容,可以用beautifulsoup, lxml.etree,re来截取内容


4.应对IP被封的方法


4.1 使用UA伪装成浏览器进行访问

4.2 延长每次爬取的时间间隔

4.3 使用代理IP进行爬取


5.常用的编码与解码方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值