【问题标题】:Beautiful Soup find() returns None?Beautiful Soup find() 返回无?
【发布时间】:2018-07-26 00:46:43
【问题描述】:

我正在尝试解析此 website 上的 HTML。

我想用class = "post-subject"从所有这些span元素中获取文本

例子:

<span class="post-subject">Set of 20 moving boxes (20009 or 20011)</span>

<span class="post-subject">Firestick/Old xbox games</span>

当我在下面运行我的代码时,soup.find() 返回None。不知道怎么回事?

import requests
from bs4 import BeautifulSoup


page = requests.get('https://trashnothing.com/washington-dc-freecycle?page=1')
soup = BeautifulSoup(page.text, 'html.parser')

soup.find('span', {'class': 'post-subject'})

【问题讨论】:

  • 如果您在该页面上运行document.querySelector('.post-subject'),也不会返回任何内容。你在哪里看到类为post-subject 的元素?您是否必须先运行搜索或与页面交互?如果是这样,您需要在调用 BeautifulSoup 之前执行此操作...
  • 该页面需要登录。查看mechanizeSelenium,了解以交互方式访问网页的方法。

标签: python web-scraping beautifulsoup


【解决方案1】:

为了帮助您开始,以下应该加载您需要获得正确的gecko driver 的页面,然后可以使用 Selenium 实现。我没有看到您链接的页面上的课程:post-subject,但您可以自动点击登录按钮:

availbutton = driver.find_element_by_id('buttonAvailability_1')
availbutton.click()


from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('https://trashnothing.com/washington-dc-freecycle?page=1')

html = driver.page_source
soup = BeautifulSoup(html,'lxml')
print(soup.find('span', {'class': 'post-subject'}))

【讨论】:

    【解决方案2】:

    我有同样的问题。只需将html.parser 更改为html5lib 并繁荣。那时它正在工作。使用soup.find_all() 而不是soup.find() 作为函数返回多个对象也是一种好习惯

    【讨论】:

    • 遇到了同样的问题。谢谢您的回答。它工作:)
    猜你喜欢
    • 2012-07-30
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    相关资源
    最近更新 更多