使用selenium和python自动访问下一页

2024-10-03 13:18:18 发布

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

我目前正在编写一个python selenium脚本来Likibu.com网站“,这是一个网站,提供短期住宿,如Airbnb,预订。。。我已经成功地获得了第一页中存在的所有数据,并将它们保存在一个csv文件中,但问题是有37页,我还想废弃这些页中存在的数据。我管理的代码如下:

driver.get("https://www.likibu.com/")
page = driver.page_source
soup = BeautifulSoup(page, "lxml")
driver.get("https://www.likibu.com/{0}".format(soup.find(rel=re.compile("nofollow")).attrs["href"]))

您可以在这里找到网页的源代码:

<ul class="pagination"> <li class="disabled"><a href="#">«</a></li> <li class="active"><a class="" rel="nofollow" href="https://www.likibu.com/fr/search/39tuzgbpnycdv7tkj102g?guests=2&amp;destination_id=4094&amp;page=1">1</a></li> <li><a class="" rel="nofollow" href="https://www.likibu.com/fr/search/39tuzgbpnycdv7tkj102g?guests=2&amp;destination_id=4094&amp;page=37">37</a></li> <li><a class="" rel="nofollow" href="https://www.likibu.com/fr/search/39tuzgbpnycdv7tkj102g?guests=2&amp;destination_id=4094&amp;page=2">»</a></li>

Tags: httpscomsearchwwwdriverpagelifr
2条回答

任何时候你都要取消多个网页,你必须弄清楚网址是如何变化的。就你而言:

root = 'https://www.likibu.com/fr/search/39yrzgbpnycdv7tkj132g?guests=2&page='

page_number = 0
while true:
    page_number +=1
    try: 
        url = root + str(page_number)
        ### CODE #####
    except:
        ### terminare / print something ####

注意:我在您发布的链接中添加了“&;page=”。尽管如此,它不会显示在第一页的url中。它还在出口。如果添加“&;page=1”,它将给出玩具的第一页。你知道吗

我用boucle修正了 如果为真:

    if not driver.find_elements_by_xpath("//*[contains(text(), 'Suivant')]"):
        break
    link=WebDriverWait(driver, 1530).until(expected_conditions.element_to_be_clickable((By.LINK_TEXT, "Suivant")))
    link.click()
    next_page = driver.find_element_by_css_selector('#pnnext')
    next_page.click()
    time.sleep(5)"""

相关问题 更多 >