Python爬虫总结

本文介绍了使用Python进行网络爬虫的基本操作,包括不使用代理和使用代理的方式获取网页内容,利用Cookie进行登录状态保持,以及如何发送表单数据。此外还讲解了如何设置HTTP头部来模拟浏览器行为。

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

基本的读取
import urllib2
http=urllib2.urlopen("http://xxxxx").read().decode('utf-8')


使用代理
import urllib2
proxy=urllib2.ProxyHandler({'http':'http://xxxxxx:xxxx'})
opener=urllib2.build_opener(proxy,urllib2.HTTPHandler)
urllib2.install_opener(opener)
html=urllib2.urlopen("xxxxxxx").read().decode('utf-8')


使用cookie
import urllib2,cookielib
cookies=urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener=urllib2.build_opener(cookies,urllib2.HTTPHandler)
urllib2.install_opener(opener)
html=urllib2.urlopen('xxxxxxx').read()

同时使用代理和cookie时更改
opener=urllib2.build_opener(proxy,cookies,urllib2.HTTPHandler)


表单的处理
要先截获报文,这里举例post内是username,passwd,login_submint
import urllib2
postdata=urllib2.urlencode({
'username':'xxxxxx',
'passwd':'xxxxxx',
'login_submint':'登录'
})
然后生成http请求再发送
req=urllib2.Request(
url='xxxxxxxxx',
data=postdata
)
result=urllib2.urlopen(req).read()



伪装浏览器行为
headers={'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}

req=urllib2.Request(
url='xxxxxxxxx',
data=postdata,
headers=headers
)
result=urllib2.urlopen(req).read()



反盗链
headers中加入Referer

转载于:https://www.cnblogs.com/lonenysky/p/4842694.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值