使用 python 3.x beautiful soup 和 urrllib.request 抓取数据
Scraping Data using python 3.x beautiful soup and urrllib.request
我最近刚开始 python,作为一个项目,我被要求学习如何从网站上抓取数据,但我很困惑,因为我对 html 更陌生,所以当我在python
price_box = soup.find('div', attrs={'class':'price'})
我没看到 class 名称在 https://www.bloomberg.com/quote/SPX:IND.
上简单地显示为 'price' 的股票价格
对我来说,class 定义如下
跨度class="priceText__1853e8a5">2,711.66
有人可以向我解释我遗漏了什么或我的错误在哪里吗?
编辑:我一直在使用这个网站来提供帮助,我只是复制了代码并且它可以工作,但是当我检查元素以亲自查看时,我看不到发生了什么。
https://medium.freecodecamp.org/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe
具体回答你的问题是可以用class_='className'
代替匹配标签div
s和classattr
s。您的代码中的问题是 HTML 标记 class 是 'priceText__1853e8a5'
而不是 'price'
由于您要抓取的网页内容不是静态的,而是通过服务器端或客户端脚本填充的,因此您必须在抓取页面之前让信息填充。我为此使用了 Selenium 并添加了 time.sleep(5)
以等待 5 秒以加载信息。然后我使用 browser.page_source
来获取页面的源代码。最后,我能够将该页面源放入 soup
并在汤中找到标签以从中提取文本。
附带说明一下,我使用 find_all()
而不是 find()
的原因是因为我不知道是否会有更多具有相同 class 的标签。
from selenium import webdriver
from bs4 import BeautifulSoup
import time
browser = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\selenium\webdriver\chromedriver_win32\chromedriver.exe")
# above is my path to chromedriver, replace it with your own.
browser.maximize_window()
browser.get('https://www.bloomberg.com/quote/SPX:IND')
time.sleep(5) # wait 5 seconds for the page to load the js
pageSource = browser.page_source
soup = BeautifulSoup(pageSource, 'html.parser')
prices = soup.find_all(class_='priceText__1853e8a5')
price = prices[0].text
print(price)
我最近刚开始 python,作为一个项目,我被要求学习如何从网站上抓取数据,但我很困惑,因为我对 html 更陌生,所以当我在python
price_box = soup.find('div', attrs={'class':'price'})
我没看到 class 名称在 https://www.bloomberg.com/quote/SPX:IND.
上简单地显示为 'price' 的股票价格对我来说,class 定义如下
跨度class="priceText__1853e8a5">2,711.66
有人可以向我解释我遗漏了什么或我的错误在哪里吗?
编辑:我一直在使用这个网站来提供帮助,我只是复制了代码并且它可以工作,但是当我检查元素以亲自查看时,我看不到发生了什么。
https://medium.freecodecamp.org/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe
具体回答你的问题是可以用class_='className'
代替匹配标签div
s和classattr
s。您的代码中的问题是 HTML 标记 class 是 'priceText__1853e8a5'
而不是 'price'
由于您要抓取的网页内容不是静态的,而是通过服务器端或客户端脚本填充的,因此您必须在抓取页面之前让信息填充。我为此使用了 Selenium 并添加了 time.sleep(5)
以等待 5 秒以加载信息。然后我使用 browser.page_source
来获取页面的源代码。最后,我能够将该页面源放入 soup
并在汤中找到标签以从中提取文本。
附带说明一下,我使用 find_all()
而不是 find()
的原因是因为我不知道是否会有更多具有相同 class 的标签。
from selenium import webdriver
from bs4 import BeautifulSoup
import time
browser = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\selenium\webdriver\chromedriver_win32\chromedriver.exe")
# above is my path to chromedriver, replace it with your own.
browser.maximize_window()
browser.get('https://www.bloomberg.com/quote/SPX:IND')
time.sleep(5) # wait 5 seconds for the page to load the js
pageSource = browser.page_source
soup = BeautifulSoup(pageSource, 'html.parser')
prices = soup.find_all(class_='priceText__1853e8a5')
price = prices[0].text
print(price)