【发布时间】:2016-12-19 17:16:18
【问题描述】:
我正在使用 Python 3.5 和 beautifulsoup (bs4) 和 urllib。我将附加的代码返回一个页面的所有链接。
我如何循环它以便它在网站的所有页面上运行,使用在每个页面上找到的链接来指示接下来要抓取哪些页面。因为我不知道我需要走多少跳。
我当然尝试过循环播放它,但它永远不会停止,因为页面包含指向我已经扫描过的页面的链接。我已经尝试创建一组我扫描过的链接,放入 IF not in set ...但它再次永远运行。
import bs4
import re
import urllib.request
website = 'http://elderscrolls.wikia.com/wiki/Skyrim'
req = urllib.request.Request(website)
with urllib.request.urlopen(req) as response:
the_page = response.read()#store web page html
dSite = bs4.BeautifulSoup(the_page, "html.parser")
links = []
for link in dSite.find_all('a'):#grab all links on page
links.append(link.get('href'))
siteOnly = re.split('/', website)
validLinks = set()
for item in links:
if re.search('^/' +siteOnly[3] + '/', str(item)):#filter links to local website
newLink = 'http://' + str(siteOnly[2]) + str(item)
validLinks.add(newLink)
print(validLinks)
【问题讨论】:
-
你的实际目标是什么?访问网站上的每个页面,尤其是 wiki,将花费很长时间,页面太多了。这表明存在更大的问题/误解。
-
我写的脚本已经完成了……是的,需要一两个小时。我的脚本运行,它实际上会找到所有链接(使文本文档的大小约为 200KB,只是链接的大小。但是,它会停止寻找新的...但不会停止。我正在努力编写检查它何时运行没有新的链接要停止。
标签: python web-scraping beautifulsoup