当前位置:   article > 正文

Python 网络爬虫进阶

Python 网络爬虫进阶

1. 确定 URL 并抓取页面代码,添加headers

  1. from urllib import request
  2. import re
  3. # 定义url
  4. page = 100
  5. url = 'https://tieba.baidu.com/f?kw=%E5%BC%B1%E6%99%BA&ie=utf-8&pn='+str(page)
  6. try:
  7. headers ={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36'}
  8. # 定义请求,传入请求头
  9. req = request.Request(url,headers=headers)
  10. # 打开网页
  11. resp = request.urlopen(req)
  12. # 打印响应,解码
  13. # print(resp.read().decode('utf-8'))
  14. content = resp.read().decode('utf-8')
  15. print(content)
  16. except request.URLError as e:
  17. # 打印响应码
  18. if hasattr(e,'code'):
  19. print(e.code)
  20. # 打印异常原因
  21. if hasattr(e,'reason'):
  22. print(e.reason)

2.查看爬取的内容,并匹配正则表达式

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/848636
推荐阅读
相关标签
  

闽ICP备14008679号