python - 使用 beautifulsoup 查找标题标签内的链接

标签 python web-scraping beautifulsoup

我正在尝试收集页面上所有标签内的所有链接,并对 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/

相关文章:

python - 属性错误 : 'list' object has no attribute 'replace' during change array

python - BeautifulSoup 输出可以发送到浏览器吗?

python beautiful soup 在类标签后立即获取中文

python - 三列 Pandas 中具有多个条件的 cumsum

python - 在 Python 中仅打印有效数字

python - urllib2 HTTP 错误 400 : Bad Request

node.js - 如何使用 puppeteer js 抓取多级链接?

Python3.6 属性错误: module 'asyncio' has no attribute 'run'

php - 带有 Job Queue 系统的 PHP/Laravel 中的逻辑代码

r - 使用 R 在雅虎财经上查找 Xpath