我正在尝试收集页面上所有标签内的所有链接,并对 125 个页面执行此操作。我创建了以下循环,但它没有获取任何链接,但也没有给我任何错误消息。
for i in xrange(125,1,-1):
page = urllib2.urlopen("http://www.freedomworks.org/issue/budget-spending?page={}".format(i))
soup = BeautifulSoup(page.read())
snippet = soup.find_all('h3')
with io.open('FWurl.txt', 'a', encoding='utf8') as logfile:
for link in snippet.find_all('a'):
fulllink = link.get('href')
logfile.write(fulllink + "\n")
我认为这正是 BeautifulSoup 的目的,但我不明白。预先感谢您。
最佳答案
我认为问题是执行 snippet.find_all
会引发异常 - snippet
显然是一个 ResultSet
对象,您需要迭代它以便实际访问每个单独的 h3 元素。
将文件修改为以下内容后,我能够检索到您正在查找的数据:
with io.open('FWurl.txt', 'a', encoding='utf8') as logfile:
for i in xrange(125, 1, -1):
page = urllib2.urlopen("http://www.freedomworks.org/issue/budget-spending?page={}".format(i))
soup = BeautifulSoup(page.read())
snippet = soup.find_all('h3')
for h3 in snippet:
for link in h3.find_all('a'):
logfile.write(link.get('href') + "\n")
注意:我不确定每个“h3”是否有多个“a”标签,因此为了安全起见,我迭代了 h3.find_all('a')
。如果每个 h3
只有一个 a
,您可以通过获取第一个元素(如果存在)来提高代码效率。
关于python - 使用 beautifulsoup 查找标题标签内的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25841212/