用python写网络爬虫 -从零开始 4 用正则表达式 编写链接爬虫

通过之前的学习,我们编写了两个基本的爬虫。但对于一些内容大的网站,我们就需要对其进行跟踪链接,利用正则表达式来确定需要下载的页面。
1.正则表达式 下载链接 ,其中 urlparse 模块用来实现相对路径转换成绝对路径,通过一个
import re
import urlparse



def link_crawler(seed_url, link_regex):
"""Crawl from the given seed URL following links matched by link_regex
"""
crawl_queue = [seed_url] # the queue of URL's to download
while crawl_queue:
url = crawl_queue.pop()
html = download(url)
# filter for links matching our regular expression
for link in get_links(html):
if re.match(link_regex, link):
# add this link to the crawl queue
crawl_queue.append(link)


def get_links(html):
"""Return a list of links from html
"""
# a regular expression to extract all links from the webpage
webpage_regex = re.compile('<a[^>]+href=["\'](.*?)["\']', re.IGNORECASE)
# list of all links from the webpage
return webpage_regex.findall(html)


if __name__ == '__main__':
link_crawler('http://example.webscraping.com', '/(index|view)')


转载于:https://www.cnblogs.com/mrruning/p/7638523.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值