鱼C论坛

 找回密码
 立即注册
查看: 1788|回复: 1

Python爬虫的一点问题

[复制链接]
发表于 2020-2-3 19:24:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. # 网站地图爬虫

  2. import urllib.request
  3. from urllib.error import URLError, HTTPError, ContentTooShortError
  4. import re

  5. def download(url, user_agent='wswp', num_retries=2, charset='utf-8'):
  6.     print('Downloading:', url)
  7.     request = urllib.request.Request(url)
  8.     request.add_header('User-Agent', user_agent)
  9.     try:
  10.         resp = urllib.request.urlopen(request)
  11.         cs = resp.headers.get_content_charset()
  12.         if not cs:
  13.             cs = charset
  14.         html = resp.read().decode(cs)
  15.     except (URLError, HTTPError, ContentTooShortError) as e:
  16.         print('Download Error:', e.reason)
  17.         html = None
  18.         if num_retries > 0:
  19.             if hasattr(e, 'code') and 500 <= e.code < 600:
  20.                 return download(url, num_retries-1)
  21.         return html

  22. def crawl_sitemap(url):
  23.     # download the sitemap file
  24.     sitemap = download(url)
  25.     # extract the sitemap links
  26.     links = re.findall('<loc>(.*?)</loc>', sitemap)
  27.     # download each link
  28.     for link in links:
  29.         html = download(link)

  30. crawl_sitemap('http://http://example.python-scraping.com/sitemap.xml')
复制代码


这是从书里面打出来的代码,有几个问题:
1.cs这变量是什么东西?
2.resp.headers.get_content_charset()整个headers和get_content_charset是哪里面的函数,百度了没找着
3.if hasattr(e, 'code') and 500 <= e.code < 600:这里面code是什么,e.code又是什么
4.links = re.findall('<loc>(.*?)</loc>', sitemap)      <loc>(.*?)</loc>这东西应该是正则表达式吧,应该是什么样?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-2-4 10:34:36 | 显示全部楼层
这都啥时候了还urllib呢
换一个http的请求库吧。

知乎搜索 python requests
然后好好看看
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-22 02:52

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表