【问题标题】:scrape websites using BeautifulSoup使用 BeautifulSoup 抓取网站
【发布时间】:2019-12-15 10:23:17
【问题描述】:

我在抓取时遇到属性错误

import urllib2
from bs4 import BeautifulSoup

quote_page ='https://www.bloomberg.com/quote/SPX:IND'
page = urllib2.urlopen(quote_page)

soup = BeautifulSoup(page,'html.parser')

name_box = soup.find('h1', attires ={'class': 'name'})

name = name_box.text.strip()
print name

Traceback(最近一次通话最后一次):

文件“word1.py”,第 11 行,在

name = name_box.text.strip()

AttributeError: 'NoneType' 对象没有属性 'text'

Viveks-MacBook-Pro:py vivek$

【问题讨论】:

  • attires 是什么错字?

标签: python beautifulsoup


【解决方案1】:

当你这样做时

print(name_box)

你会得到

 None
Traceback (most recent call last):
  File "C:/Users/devsurya/python/demo programs/b4s.py", line 13, in <module>
    name = name_box.text.strip()
AttributeError: 'NoneType' object has no attribute 'text'

当你这样做时 -

print(soup)    ## it says following message with weird html and css

我们从您的计算机网络中检测到异常活动

soup.find('h1', attires ={'class': 'name'}) 应该是soup.find('h1', {'class': 'companyName__99a4824b'})

【讨论】:

    【解决方案2】:

    假设您想要公司名称,我将与请求一起使用,并且需要几个标头(您需要测试它是否会随着时间的推移始终如一地执行)。我使用 css 属性 = 值选择器来获取适当的元素,并以运算符 ^ 开头,以防值是动态的,即我假设 companyName 的恒定起始字符串。这使得它更适用于其他请求。

    import requests
    from bs4 import BeautifulSoup as bs
    
    quote_page ='https://www.bloomberg.com/quote/SPX:IND'
    page = requests.get(quote_page, headers = {'User-Agent':'Mozilla/5.0', 'accept-language':'en-US,en;q=0.9'})
    soup = bs(page.content,'lxml')
    name_box = soup.select_one('[class^=companyName]')
    name = name_box.text.strip()
    print(name)
    

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多