试图让Selenium下载基于JavaScript的数据…我瘦了

2024-04-26 21:36:27 发布

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

我正在尝试从以下URL下载数据

https://www.nissanusa.com/dealer-locator.html

我想到了这个,但它实际上并没有获取任何数据

import urllib.request
from bs4 import BeautifulSoup

url = "https://www.nissanusa.com/dealer-locator.html"
text = urllib.request.urlopen(url).read()
soup = BeautifulSoup(text)

data = soup.findAll('div',attrs={'class':'dealer-info'})
for div in data:
    links = div.findAll('a')
    for a in links:
        print(a['href'])

我以前做过几次,过去也一直有效。我猜数据是由JavaScript根据用户选择的过滤器动态生成的,但我不确定。我读过Selenium可以用来自动化web浏览器,但我从来没有用过它,我也不知道从哪里开始。最后,我尝试以这种格式获取数据,如下图所示。无论是打印在控制台窗口,或下载到CSV,将是罚款

enter image description here

最后,网站是如何获得数据的?无论我是进入纽约市还是旧金山,地图和数据集相对于应用的过滤器都会发生变化,但是URL根本不会发生变化。提前谢谢


Tags: 数据httpsimportdivcomurlrequesthtml
1条回答
网友
1楼 · 发布于 2024-04-26 21:36:27

使用selenium打开/导航到页面,然后将页面源代码传递给BeautifulSoup

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from bs4 import BeautifulSoup

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 10)

url = 'https://www.nissanusa.com/dealer-locator.html'
browser.get(url)

time.sleep(10) // wait page open complete

html = browser.page_source
soup = BeautifulSoup(html, "html.parser")

data = soup.findAll('div',attrs={'class':'dealer-info'})
for div in data:
    links = div.findAll('a')
    for a in links:
        print(a['href'])

相关问题 更多 >