2017-10-05 98 views
0

我试图从网站刮表,但我似乎无法用Python中的Beautifulsoup弄清楚。我不知道是否因为表格格式,但我基本上想把这个表格变成CSV。在Python中使用美丽的汤网页刮 - JavaScript表

from bs4 import BeautifulSoup 
import requests 

page = requests.geenter code heret("https://spotwx.com/products/grib_index.php?model=hrrr_wrfprsf&lat=41.03399&lon=-73.76291&tz=America/New_York&display=table") 
soup = BeautifulSoup(page.content, 'html.parser') 
print(soup.prettify) 

有关如何隔离此数据表的任何建议?我查了很多Beautifulsoup教程,但HTML看起来与大多数引用不同。非常感谢您的帮助 -

回答

1

试试这个。该网站的表格会动态生成,因此只能使用requests才能得到结果。

from selenium import webdriver 
from bs4 import BeautifulSoup 
import csv 

outfile = open("spotwx.csv", "w", newline='') 
writer = csv.writer(outfile) 

driver = webdriver.Chrome() 
driver.get("https://spotwx.com/products/grib_index.php?model=hrrr_wrfprsf&lat=41.03399&lon=-73.76291&tz=America/New_York&display=table") 
soup = BeautifulSoup(driver.page_source, 'lxml') 

driver.quit() 
titles = soup.select("table#example")[0] 
list_row =[[tab_d.text for tab_d in item.select('td')] 
       for item in titles.select('tr')] 

for data in list_row: 
    print(' '.join(data)) 
    writer.writerow(data) 
outfile.close() 
+0

非常感谢您的回复。我不熟悉Webdriver,但我不需要实时刷新(除非绝对必要,否则不希望使用Webdriver)。看起来,简单地做一个请求拉取在soup.prettify代码中显示了必要的数据,但我不知道如何将它提取到表中。再次感谢您的帮助 ! –

+0

当我尝试上面的代码时,出现错误 selenium.common.exceptions.WebDriverException:消息:'chromedriver'可执行文件需要位于PATH中。请参阅https://sites.google.com/a/chromium.org/chromedriver/home –

+0

第一个应该可以工作。如果没有,那么去第二个。 1.'driver = webdriver.Chrome('C:/path/to/chromedriver.exe')'2.'driver = webdriver.Chrome('/ path/to/chromedriver')'.Btw,你必须根据到你的系统,我的意思是路径。谢谢。 – SIM