【问题标题】:Looping through home listings with Selenium使用 Selenium 循环浏览房屋列表
【发布时间】:2020-05-09 04:46:34
【问题描述】:

我正在尝试使用 Selenium 循环浏览主页列表站点,但无法让 while 循环遍历页面。 The pages present on the web page as shown, with no "Previous" or "Next" button. 我不确定如何找到该站点的列表页总数,但我正在测试这个 while 循环 20(用 max_page_count = 20 看到),因为我知道至少有 20 页列表。我正在考虑两 (2) 种迭代页面的方法,但每种方法都停留在不同的阶段:

  1. 使用:https://www.tinyhomebuilders.com/tiny-house-marketplace/search?page={}.format(page) 并创建一个计数器来浏览页面。
  2. 使用 Selenium 的 click 功能点击提供的图片中显示的页面元素。

我已经检查并知道我可以从页面上刮掉价格元素,但我发现点击功能不起作用。

这是我的代码:

driver_location = 'C:/Users/oefel/Downloads/geckodriver-v0.26.0-win64'
os.environ['webdriver.firefox.driver'] = driver_location 
driver = webdriver.Firefox(driver_location)
driver.get("https://www.tinyhomebuilders.com/tiny-house-marketplace/search")
driver.implicitly_wait(50)
driver.maximize_window()

tiny_house_price = []

page_count = 0
max_page_count = 20

while (page_count < max_page_count):
        html_soup = BeautifulSoup(driver.page_source, 'lxml')

        scraped_price = driver.find_elements_by_css_selector("div.card-body > div.price")
        for price in scraped_price:
                tiny_house_price.append(price.text)
        print(tiny_house_price)

        page = driver.find_elements_by_css_selector('.pagination > li > a.href').click()

        page_count += 1

非常感谢任何帮助!

谢谢!

【问题讨论】:

    标签: selenium pagination


    【解决方案1】:

    在这种情况下,您不需要 selenium 来获取文本。您可以通过向页面发出 get 请求并从中获取 html 来获取页面文本。页码作为 URL 参数传递,您可以遍历它并获得所需的输出。示例如下:

    import requests
    from bs4 import BeautifulSoup
    
    tiny_house_price = []
    
    page_count = 1
    max_page_count = 20
    
    while (page_count < max_page_count):
        r = requests.get('https://www.tinyhomebuilders.com/tiny-house-marketplace/search?page={}'.format(page_count))
        html_soup = BeautifulSoup(r.text, 'html.parser')
        scraped_price = html_soup.select("div.card-body > div.price")
        for price in scraped_price:
            tiny_house_price.append(price.text.strip())
        print(tiny_house_price)
    
        page_count += 1
    

    由于选择器不正确,您的点击无法正常工作。您必须通过链接文本找到元素并单击。链接文本将是页数。

    如果您也想使用 selenium,可以使用上面使用的相同页面 url 参数逻辑。您只需要使用 selenium 打开网页并获取源代码并在获取 html 后导航到新页面。

    【讨论】:

      猜你喜欢
      • 2018-12-08
      • 2016-05-27
      • 1970-01-01
      • 2020-10-14
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      相关资源
      最近更新 更多