无法从websi中使用BeautifulSoup废弃表数据

2024-04-28 06:33:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在遵循一个在线教程(https://www.analyticsvidhya.com/blog/2015/10/beginner-guide-web-scraping-beautiful-soup-python/),该教程介绍如何在web上废弃html表。当我遵循教程时,我能够废弃表数据,但是当我试图从这个(https://www.masslottery.com/games/lottery/search/results-history.html?game_id=15&mode=2&selected_date=2019-03-04&x=12&y=11)网站中废弃数据时,我却无法这样做。你知道吗

我以前试过用scrapy,但得到了同样的结果。你知道吗

这是我使用的代码。你知道吗

import urllib.request

wiki = "https://www.masslottery.com/games/lottery/search/results-history.html?game_id=15&mode=2&selected_date=2019-03-04&x=12&y=11"
page = urllib.request.urlopen(wiki)
from bs4 import BeautifulSoup
soup = BeautifulSoup(page, "lxml")


all_tables=soup.find_all('table')


right_table=soup.find('table', class_='zebra-body-only')
print(right_table)

这就是我在终端上运行代码时得到的结果

<table cellspacing="0" class="zebra-body-only">
<tbody id="target-area">
</tbody>
</table>

虽然当我用谷歌chrome浏览大众彩票网站时,我看到的就是这个

<table cellspacing="0" class="zebra-body-only"                                  <tbody id="target-area">
<tr class="odd">
<th>Draw #</th>
<th>Draw Date</th>
<th>Winning Number</th>
<th>Bonus</th>
</tr>
<tr><td>2107238</td>
<td>03/04/2019</td>
<td>01-04-05-16-23-24-27-32-34-41-42-44-47-49-52-55-63-65-67-78</td><td>No Bonus</td>
</tr>
<tr class="odd">
<td>2107239</td>
<td>03/04/2019</td>
<td>04-05-11-15-19-20-23-24-25-28-41-45-52-63-64-68-71-72-73-76</td><td>4x</td>
</tr> 
....(And so on)

我希望能够从这个表中提取数据。你知道吗


Tags: 数据httpscomidonlyhtmlwwwtable
3条回答

发生这种情况的原因是网站再次调用以加载结果。初始链接只加载页面,而不加载结果。使用chromedev工具检查请求,您将能够找到需要复制以获得结果的请求。你知道吗

这意味着要获得结果,只需调用上面提到的请求,而不必调用网页。你知道吗

幸运的是,您必须调用的端点已经是一个很好的JSON格式。你知道吗

GET https://www.masslottery.com/data/json/search/dailygames/history/15/201903.json?_=1555083561238

我假设1555083561238是时间戳。你知道吗

是的,我会把你得到的数据保存在一个文件里,看看你要找的东西是否真的存在。 打开('资料.html','w')作为f: f、 写(回复.text)你知道吗

unicode,请尝试: 导入编解码器 编解码器.打开(fp,'w','utf-8')表示f:

如果你看不到你在那里寻找什么,你将不得不找出正确的网址加载,检查chrome开发者选项 这通常很难

简单的方法是使用硒 一定要等到你要找的东西出现在页面上 (这是动态的)

页面是动态的,因此在您发出请求之后呈现。您可以a)使用JC1的解决方案并访问json响应。或者您可以使用Seleneium模拟打开浏览器,呈现页面,然后抓取表格:

from bs4 import BeautifulSoup
from selenium import webdriver


url = 'https://www.masslottery.com/games/lottery/search/results-history.html?game_id=15&mode=2&selected_date=2019-03-04&x=12&y=11'  

driver = webdriver.Chrome()
driver.get(url)
page = driver.page_source

soup = BeautifulSoup(page, "lxml")

all_tables=soup.find_all('table')


right_table=soup.find('table', class_='zebra-body-only')

另请注意:通常如果我看到<table>标记,我会让Pandas替我做这项工作(注意,我被阻止访问站点,因此无法测试这些):

import pandas as pd
from selenium import webdriver


url = 'https://www.masslottery.com/games/lottery/search/results-history.html?game_id=15&mode=2&selected_date=2019-03-04&x=12&y=11'  

driver = webdriver.Chrome()
driver.get(url)
page = driver.page_source

# will return a list of dataframes
tables = pd.read_html(page)

# chose the dataframe you want from the list by it's position
df = tables[0]

相关问题 更多 >