使用 BeautifulSoup 通过超链接访问表格数据

Accessing tabular data via hyperlinks with BeautifulSoup

关于使用 BeautifulSoup,我仍然有一些不明白的地方。我可以用它来解析网页的原始 HTML,此处 "example_website.com":

from bs4 import BeautifulSoup # load BeautifulSoup class
import requests 
r  = requests.get("http://example_website.com")
data = r.text
soup = BeautifulSoup(data)
# soup.find_all('a') grabs all elements with <a> tag for hyperlinks    

然后,要检索并打印具有 'href' 属性的所有元素,我们可以使用 for 循环:

for link in soup.find_all('a'):
    print(link.get('href')) 

我不明白的是:我有一个包含多个网页的网站,每个网页都列出了几个指向带有表格数据的单个网页的超链接。

我可以使用 BeautifulSoup 来解析主页,但如何使用相同的 Python 脚本来抓取第 2 页、第 3 页等页面?您如何 "access" 通过 'href' 链接找到的内容?

有没有办法编写 python 脚本来执行此操作?我应该使用蜘蛛吗?

你肯定可以用 requests+BeautifulSoup 做到这一点。这将是阻塞性质的,因为您将一个接一个地处理提取的 link,并且在完成当前处理之前不会继续进行下一个 link。实施示例:

from urlparse import urljoin

from bs4 import BeautifulSoup 
import requests 

with requests.Session() as session:    
    r = session.get("http://example_website.com")
    data = r.text
    soup = BeautifulSoup(data)

    base_url = "http://example_website.com" 
    for link in soup.find_all('a'):
        url = urljoin(base_url, link.get('href'))

        r = session.get(url)
        # parse the subpage

不过,它可能很快就会变得复杂和缓慢。

您可能需要切换到 Scrapy web-scraping framework which makes web-scraping, crawling, following the links easy (check out CrawlSpider 和 link 提取器),快速且非阻塞性质(它基于 Twisted)。