javascript - Python Web Scraper - 由页面 JavaScript 定义的每个页面的有限结果
问题描述
我无法在此网站上获得完整的搜索结果: https ://www.gasbuddy.com/home?search=67401&fuel= 1 此链接是我遇到问题的搜索结果之一。问题是它只显示前 10 个结果(我知道,这是一个常见问题,已在 stackoverflow 上的多个线程中进行了描述 - 但在其他地方找到的解决方案在这里不起作用。)页面的 html 似乎是由javascript 函数,它不会将所有结果嵌入到页面中。我尝试使用一个函数来访问“更多 [...] Gas Price”按钮中提供的链接,但这也不会产生完整的结果。有没有办法访问这个完整的列表,还是我不走运?
这是我用来获取信息的 Python:
# Gets the prices from gasbuddy based on the zip code.
def get_prices(zip_code, store):
search = zip_code
# Establishes the search params to be passed to the website.
params ={'search': search, 'fuel': 1}
# Contacts website and make the search.
r = requests.get('https://www.gasbuddy.com/home', params=params, cookies={'DISPLAYNUM': '100000000'})
# Turn the results of the above into Beautiful Soup object.
soup = BeautifulSoup(r.text, 'html.parser')
# Searches out the div that contains the gas station information.
results = soup.findAll('div', {'class': 'styles__stationListItem___xKFP_'})
解决方案
使用硒。设置起来有点麻烦,但听起来这就是您所需要的。
在这里,我用它来点击网站的“显示更多”按钮。在我的确切项目中查看更多信息。
from selenium import webdriver
url = 'https://www.gofundme.com/discover'
driver = webdriver.Chrome('C:/webdriver/chromedriver.exe')
driver.get(url)
for elem in driver.find_elements_by_link_text('Show all categories'):
try:
elem.click()
print('Succesful click')
except:
print('Unsuccesful click')
source = driver.page_source
driver.close()
所以基本上你需要找到你需要点击显示更多信息的元素的名称,或者你需要使用 webdriver 来向下滚动网页。
推荐阅读
- python - 为什么我收到此 django 连接中止错误
- amazon-web-services - Website does not update - Even after Invalidation through AWS Website, CLI and changing metadata of S3 Bucket
- selenium-webdriver - Selenium Java - Chrome 83. 0 - Authentication required. Basic Authentication required. Unable to login
- reactjs - Reactstrap - 如何在按钮内正确渲染微调器?
- php - is there any option print 0 if array position is null?
- c - How is this function printing an integer in binary form?
- python - Telegram API 不适用于用户名 - 400。错误请求:未找到聊天
- node.js - 在 node.js 中提供 gzipped 构建
- algorithm - Big-O algorithm
- php - Woocommerce - 重定向到已收到订单的页面,但未显示订单详细信息