request库笔记

requests中不需要转换为URL上的编码

携带params
dict={'key':'value'}
response=requests.get('url',params=dict)
response.url='url?key=value&key1=value'

不传参就用format格式化url

携带cookies, 用于登录
response=requests.get(url,headers=headers,cookies=Cooikes)
携带data,用于向页面发送post请求
request.post(url,data=data),不需要将data转化为url编码
ip代理
proxies = {
    'http': 'http://%(user)s:%(pwd)s@%(ip)s/' % {'user': username, 'pwd': password, 'ip': proxy},
    'https': 'http://%(user)s:%(pwd)s@%(ip)s/' % {'user': username, 'pwd': password, 'ip': proxy}
}
req = requests.get(url=url_page, proxies=proxies, headers=headers)

content和text区别
text直接获得现成的字符串,但是有时候显示错误
content获得二进制数据,可以通过.decode(utf-8)获得中文字符串数据

属性作用
.status_code状态码
.text网页内容
.cookies请求网页的cookies
.url打印请求的url

json.loads()将字符串转换为python数据类型,大多字典
json.dumps()将字典转换为字符串

Xpath笔记

Xpath是一门在XML文档中查找信息的语言。可用来在xml文档中对元素和属性进行遍历。
lxml是一个HTML/XML的解析器。主要功能是如何解析和提取HTML/XML数据的。

etree.HTML(将字符串解析为HTML文档)
html=etree.HTML(test)

#toString将html文档转换为byte类型,再将其解码转换为str

result=etree.tostring(html,encoding='utf8').decode(utf-8)

可以通过这种方法格式化字符串转换为html格式

etree.parse()方法

用于解析html页面,返回一个节点树,可以通过tostring转换回去

html1 = etree.parse('xx.html', etree.HTMLParser()) 
print(html1)=<lxml.etree._ElementTree object at 0x014CE940>
两者的区别

etree.html是将爬取的网页数据再生成标准网页格式数据,但是有些时候网页不规范
etree.parse是对标准网页格式数据进行解析用的
html1 = etree.parse(‘html’, etree.HTMLParser())

#将其转换为节点树后就可以通过xpath定位
result=html.xpath(’’)

百度贴吧反爬解决:
html_new=html.replace(r'<!--','"').replace(r'-->','"')
html.xpath(html_new)
xpath乱码问题
html_data = html1.xpath('//li/a')
for i in html_data:
    result=i.text
    print(result.encode('ISO-8859-1').decode('utf-8'))  # 通过i.text输出具体内容
用于遍历删除文件夹的内容(txt,png…)
path2=os.path.join(path,'pic')
    if os.listdir(path2)!=[]:
        for i in os.listdir(path2):
            b = os.path.join(path2, i)
            os.remove(b)
用于删除目录
path1=os.path.join(path,'a.txt')
if(os.path.exists(path)):
    os.remove(path1)
用于提高爬取速率
p = Pool(MAX_WORKER_NUM)
for read in reads:
    flag+=1
    p.apply_async(xiazai, args=(read,flag))
p.close()
p.join()
获取网页内容的方法:

1.正则表达式(复习笔记)
链接: link.
2.xpath 爬取的数据是一个列表,遍历的时候,如果里面的元素还有多个元素,那么再遍历一遍,直到只有一个,就可以获得具体元素,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值