【问题标题】:Replacement of nth-child to nth-of-type gives an unexpected error将 nth-child 替换为 nth-of-type 会产生意外错误
【发布时间】:2018-11-30 01:34:52
【问题描述】:

我正在尝试使用 BeautifulSoup 从以下网页获取一些信息:

url = 'https://web.archive.org/web/20071001215911/http://finance.rambler.ru'

在我的浏览器 (Chrome) 的帮助下,我复制了所需元素的选择器:

selector = 'body > div.fe_global > table:nth-child(6) > tbody > tr > td:nth-child(2) > table > tbody > tr > td.fe_col-left > div:nth-child(5) > table > tbody'

但是,bs4 不支持 nth-child,因此我将其替换为 nth-of-type:

selector = selector.replace('child', 'of-type')

把它涂在汤上

r = requests.get(url)
soup = BeautifulSoup(r.content, 'lxml')
selected_element = soup.select(selector=selector)

print (selected_element)

输出是 []。 我希望得到一些 HTML 代码。 这样回答的原因是什么? 感谢您的帮助。

【问题讨论】:

    标签: python parsing beautifulsoup css-selectors


    【解决方案1】:

    在选定的div 中它有 2 个表,我将选择第二个表

    from bs4 import BeautifulSoup
    import requests
    
    url = 'https://web.archive.org/web/20071001215911/http://finance.rambler.ru'
    heads = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0'}
    r = requests.get(url, headers=heads)
    soup = BeautifulSoup(r.text, 'html.parser')
    selected_element = soup.select('div[class="fe_small fe_l2"] table')[1]
    
    print (selected_element)
    

    【讨论】:

    • 编辑了答案,它没有tbody 并且必须设置用户代理。
    • 现在可以了,谢谢。尽管如此,我还是很困惑为什么 CSS 选择器在我的脚本中不起作用。
    • nth-of-typenth-child 正在选择元素的不同位置
    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2017-01-07
    • 2012-11-21
    相关资源
    最近更新 更多