【问题标题】:HTML confusion with Python BeautifulSoupHTML 与 Python BeautifulSoup 的混淆
【发布时间】:2015-05-29 15:09:30
【问题描述】:

我在 youtube 上关注 thenewboston 的教程,编译我的代码后我没有收到任何错误。

我正在尝试打印“通用行列表”以及该列表后面的所有链接;可以在此链接的底部找到 http://playrustwiki.com/wiki/List_of_Items

import requests
from bs4 import BeautifulSoup

def trade_spider(max_pages):
    page = 1
    while page <= max_pages: #makes our pages change everytime
        url = 'http://playrustwiki.com/wiki/List_of_Items' + str(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text) #find all the links in soup or all the titles
        for link in soup.findAll('a', {'class': 'a href'}): #links are a for anchors in HTML
        href = link.get('href') # href attribute
        print(href)
        page += 1

trade_spider(1)

我尝试了不同的 HTML 属性,但我认为这就是我的困惑开始的地方。我找不到正确的属性来调用我的爬虫,或者我调用了错误的属性。

请帮忙~

谢谢:)

【问题讨论】:

    标签: python-3.x web-scraping beautifulsoup html-parsing


    【解决方案1】:

    这里的想法是找到具有Generic line list 文本的元素。然后,通过find_next_sibling() 找到下一个ul 兄弟,并通过find_all() 获取里面的所有链接:

    h3 = soup.find('h3', text='Generic Line List')
    generic_line_list = h3.find_next_sibling('ul')
    for link in generic_line_list.find_all('a', href=True):
        print(link['href'])
    

    演示:

    >>> import requests
    >>> from bs4 import BeautifulSoup
    >>> 
    >>> url = 'http://playrustwiki.com/wiki/List_of_Items'
    >>> soup = BeautifulSoup(requests.get(url).content)
    >>>
    >>> h3 = soup.find('h3', text='Generic Line List')
    >>> generic_line_list = h3.find_next_sibling('ul')
    >>> for link in generic_line_list.find_all('a', href=True):
    ...     print(link['href'])
    ... 
    /wiki/Wood_Barricade
    /wiki/Wood_Shelter
    ...
    /wiki/Uber_Hunting_Bow
    /wiki/Cooked_Chicken_Breast
    /wiki/Anti-Radiation_Pills
    

    【讨论】:

    • 哇,感谢您的快速回复。我了解如果 href 为真,您的代码会迭代,因此会打印所有找到的代码。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    相关资源
    最近更新 更多