当前位置: 移动技术网 > IT编程>脚本编程>Python > Python爬虫之UserAgent的使用实例

Python爬虫之UserAgent的使用实例

2019年03月19日  | 移动技术网IT编程  | 我要评论

爆米花小店,天灾古物,天书奇谈小金龙

问题: 在python爬虫的过程中经常要模拟useragent, 因此自动生成useragent十分有用, 最近看到一个python库(fake-useragent),可以随机生成各种useragent, 在这里记录一下, 留给自己爬虫使用。

安装 pip install fake-useragent

使用案例

基本使用

from fake_useragent import useragent
ua = useragent()
ua.ie
# mozilla/5.0 (windows; u; msie 9.0; windows nt 9.0; en-us);
ua.msie
# mozilla/5.0 (compatible; msie 10.0; macintosh; intel mac os x 10_7_3; trident/6.0)'
ua['internet explorer']
# mozilla/5.0 (compatible; msie 8.0; windows nt 6.1; trident/4.0; gtb7.4; infopath.2; sv1; .net clr 3.3.69573; wow64; en-us)
ua.opera
# opera/9.80 (x11; linux i686; u; ru) presto/2.8.131 version/11.11
ua.chrome
# mozilla/5.0 (windows nt 6.1) applewebkit/537.2 (khtml, like gecko) chrome/22.0.1216.0 safari/537.2'
ua.google
# mozilla/5.0 (macintosh; intel mac os x 10_7_4) applewebkit/537.13 (khtml, like gecko) chrome/24.0.1290.1 safari/537.13
ua['google chrome']
# mozilla/5.0 (x11; cros i686 2268.111.0) applewebkit/536.11 (khtml, like gecko) chrome/20.0.1132.57 safari/536.11
ua.firefox
# mozilla/5.0 (windows nt 6.2; win64; x64; rv:16.0.1) gecko/20121011 firefox/16.0.1
ua.ff
# mozilla/5.0 (x11; ubuntu; linux i686; rv:15.0) gecko/20100101 firefox/15.0.1
ua.safari
# mozilla/5.0 (ipad; cpu os 6_0 like mac os x) applewebkit/536.26 (khtml, like gecko) version/6.0 mobile/10a5355d safari/8536.25
# and the best one, random via real world browser usage statistic
ua.random

注意:

fake-useragent 将收集到的数据缓存到temp文件夹, 例如 /tmp, 更新数据:

from fake_useragent import useragent
ua = useragent()
ua.update()

有时候会因为网络或者其他问题,出现异常(fake_useragent.errors.fakeuseragenterror: maximum amount of retries reached), 可以禁用服务器缓存(从这里踩了一个坑, 没仔细看文档的锅):

from fake_useragent import useragent
ua = useragent(use_cache_server=false)

可以自己添加本地数据文件(v0.1.4+)

import fake_useragent
# i am strongly!!! recommend to use version suffix
location = '/home/user/fake_useragent%s.json' % fake_useragent.version
ua = fake_useragent.useragent(path=location)
ua.random

其他功能用到的也不是很多,详细见文档吧。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网