《用Python写网络爬虫》第一章踩坑

教程使用环境为pyhon2.x,使用python3.x进行学习时遇到一些坑,记录下解决办法。

由于python2.x中的urllib2模组在3.x中被整合到了urllib模组中,教程中涉及urllib2的部分的代码需调整

1.4.1下载网页

urlopen:

  from urllib import request as r

   r.urlopen()

URLError:

  except r.URLError as e:

 

1.4.4链接爬虫

urlparse名字改为parse

   from urllib import parse

  link = parse.urljoin(seed_url, link)

 

1.4.4支持代理:

Request & build_opener():

  from urllib import request as r

  request = r.Request(url, headers=headers)

  opener = r.build_opener()

 

最终版本代码(bitbucket链接内):

deque:

  from collections import deque

  crawl_queue = deque([seed_url])

正则表达式(部分页面地址有所变化,因此匹配规则做部分修改):

get_links(...):

  re.compile('<a[^>]+href=["\']([^#].*?)["\']', re.I)

  link_regex ='/.*?(index|view)'

 

   

 

猜你喜欢

转载自www.cnblogs.com/hsifria/p/9903756.html