首页 > 解决方案 > 如何从

元素“id”

问题描述

我正在学习如何刮,然后我不是很先进。我从彭博社的公司描述中摘录下来。例如从这个页面(https://www.bloomberg.com/research/stocks/private/snapshot.asp?privcapId=320105

我想刮

<p id="bDescTeaser" itemprop="description">Fiat Chrysler Automobiles N.V., ...</p>


我的脚本:

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
html= 'https://www.bloomberg.com/research/stocks/private/snapshot.asp? 
privcapId=32010'
page = urlopen(html)
data = BeautifulSoup(page, 'html.parser')
text = data.find('p',id="bDescTeaser",itemprop="  ")
print(text.get_text))

如果我尝试运行我得到的程序,

AttributeError: 'NoneType' object has no attribute 'get_text'

这是我的代码还是这个特定的 webapge 的问题?

标签: pythonweb-scrapingbeautifulsoupnonetype

解决方案


在您的解决方案中,彭博阻止了您的请求。因为它认为你是一个机器人。您应该使用请求库并将用户代理作为标头发送。您将通过这种方式获得预期的输出。

import requests
from bs4 import BeautifulSoup

header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0'}
request = requests.get('https://www.bloomberg.com/research/stocks/private/snapshot.asp?privcapId=320105',headers=header)
soup = BeautifulSoup(request.text, 'html.parser')    
text = soup.find('p',id="bDescTeaser")
print(text.get_text())

推荐阅读