繁体   English   中英

使用BeautifulSoup抓取网站

[英]scrape websites using BeautifulSoup

我在抓取时遇到属性错误

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

追溯(最近一次通话):

在第11行的文件“ word1.py”中

 name = name_box.text.strip() 

AttributeError:“ NoneType”对象没有属性“ text”

Viveks-MacBook-Pro:py vivek $

当你这样做

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'})

假设您想要公司名称,我将随请求一起使用,并且需要几个标头(您将需要进行测试,以查看其是否随着时间的推移始终保持一致)。 我使用css attribute = value选择器来获取适当的元素,并使用以运算符^开头的情况(如果值是动态的),即我假设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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM