【问题标题】:Parsing large amounts of HTML for text values using BeautifulSoup使用 BeautifulSoup 为文本值解析大量 HTML
【发布时间】:2018-01-27 23:51:56
【问题描述】:

我正在使用 Selenium 和 BeautifulSoup 手动爬取列表中的网页并保存数据。我在尝试使用 findfindAll 方法时遇到了一些麻烦。

Here's the exact HTML I'm working with。我把它贴在 Pastebin 上是因为它有很多。

如果我想提取这个 HTML 中的值,比如里面的文本

<div class="item value nowrap">4 Bedrooms   3 Bathrooms</div>

或者

<td class="value" originalvalue="6229"> 6,229 sq ft </td>

我该怎么做?我试过使用以下代码:

soup = BeautifulSoup(''.join(html)) j = soup.find('item value nowrap')[0].text print j

我收到以下错误:

Traceback (most recent call last):
  File "/Users/me/PycharmProjects/crawl/main.py", line 39, in <module>
    j = soup.find('item value nowrap')[0].text
TypeError: 'NoneType' object has no attribute '__getitem__'

有人能指出我正确的方向吗?如何使用 BeautifulSoup 获取这些值?

【问题讨论】:

    标签: python selenium beautifulsoup


    【解决方案1】:

    我会这样做:

    from bs4 import BeautifulSoup
    html = """<html>...[paste your html here]...</html>"""
    soup = BeautifulSoup(html, 'lxml')
    items = soup.find_all('div', attrs={"class":'item value nowrap'})
    items = [i.text for i in items]
    values = soup.find_all('td', attrs={"class":"value"})
    values = [i.text.strip("\n") for i in values]
    

    find() 不返回列表,因此您无法像尝试那样将其编入索引 (soup.find('item value nowrap')[0].text)

    这就是我认为你想要找到的东西:

    houses = soup.find_all('div', attrs={"class":"left factsSection basicFacts sectionSeparator"})
    
    for house in houses:
        details = house.find_all('div', attrs={"class":"item"})
        print("Owner:", details[-1].find('span').text)
        print("Price/sq. foot:", details[-2].find('span').text)
    

    这会导致:

    Owner: Jones Patrick Clayton
    Price/sq. foot: $77
    

    【讨论】:

    • 真的只是想找出一种一致的方法来获取与我相关的页面上的数据。我尝试了您的解决方案并收到以下错误:AttributeError: 'str' object has no attribute 'text'
    • 我认为你已经非常接近获得你需要的东西了。这段代码对我有用(请注意,我只是对最后一行做了一个小编辑)你能告诉我哪一行给了你这个错误吗? @vipertherapper
    • 这一行:soup = BeautifulSoup(html, 'lxml') 。我使用的是 Python 2,你认为这是错误的原因吗?
    • @vipertherapper 可能,我在 python 3(Anaconda 发行版)中写了这个
    • 我设法在 Python 2 中做到了,但我遇到了这个问题,我想提取的 HTML 中的一些文本都是带有相同标签的 span 标签。如何分别提取它们?如果您想查看 HTML 本身,我想要的值是财产所有者和每平方英尺的价值。
    【解决方案2】:

    我最终做了类似于 briancaffey 的回答,但是,我使用的是 Python 2。代码如下:

    basic_facts_tags = soup.findAll('span', {'class': 'value'}) # Get basic facts
    property_owner = basic_facts_tags[1].text # Owner of the property. 
    value_per_sq_ft = basic_facts_tags[0].text # Value per sq ft according to RPR
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多