首页 > 解决方案 > 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_'})

标签: javascriptpythonweb-scrapingbeautifulsoup

解决方案


使用。设置起来有点麻烦,但听起来这就是您所需要的。

在这里,我用它来点击网站的“显示更多”按钮。在我的确切项目中查看更多信息。

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 来向下滚动网页。


推荐阅读