【问题标题】:how to get all the hyperlinks from child elements from a specific div container having multiple pages(pagination) using selenium python如何使用 selenium python 从具有多个页面(分页)的特定 div 容器中获取子元素的所有超链接
【发布时间】:2021-09-29 10:07:57
【问题描述】:

我正在尝试从this site 的父 id='search-properties' 中抓取子元素 href 属性中的链接。我首先尝试使用 find_elements_by_id 定位元素,然后使用 find_elements_by_css_selector 定位链接,但我不断得到 AttributeError: 'list' object has no attribute 'find_elements_by_css_selectors' 这样做时我尝试使用 find_elements_by_tag_name 以及 find_elements_by_xpath 而是抓取链接它实际上抓取了对我没有用的链接内的细节。所以在环顾四周后,我终于找到了这段代码

from logging import exception
from typing import Text
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
import pandas as pd
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import csv
from selenium import webdriver 
PATH = "C:/ProgramData/Anaconda3/scripts/chromedriver.exe" #always keeps chromedriver.exe inside scripts to save hours of debugging
driver =webdriver.Chrome(PATH) #preety important part
driver.get("https://www.gharbazar.com/property/search/?_q=&_vt=1&_r=0&_pt=residential&_si=0&_srt=latest")
driver.implicitly_wait(10)
house=driver.find_elements_by_tag_name("a")
# traverse list
for lnk in house:
   # get_attribute() to get all href
   print(lnk.get_attribute('href'))

这段代码的问题是它会刮掉所有的链接,这意味着它还有一些绝对不必要的链接,就像这张图片don't need javascript void 一样。 最后,对于分页,我尝试遵循这个answer,但得到了无限循环,所以我不得不删除分页代码。总之,我正在尝试获取具有 id = 'search-properties' 的多个页面的链接

【问题讨论】:

  • 网站上的右键单击被禁用了吗?
  • 是的,但是你可以通过按 ctrl+ shift+ j 来访问它
  • 好的!是的,我这样做是为了获取元素
  • 请专注于从下一页抓取链接

标签: python selenium web-scraping pagination parent-child


【解决方案1】:

我试过这个进行分页。

    from selenium import webdriver
    import time

    driver = webdriver.Chrome(executable_path="path")
    driver.implicitly_wait(10)
    driver.get("https://www.gharbazar.com/property/search/?_q=&_vt=1&_r=0&_pt=residential&_si=0&_srt=latest")
    page=2

    while True:
        nextoption = driver.find_element_by_xpath("//div[@id='pagination-div']//a[contains(text(),'>>')]")
        driver.execute_script("arguments[0].scrollIntoView(true);",nextoption)
        driver.execute_script("window.scrollBy(0,-300)")
        time.sleep(5)
        try:
            driver.find_element_by_link_text(str(page)).click()
            page += 1
            time.sleep(3)

        except Exception as e:
            print(e)
            break

    driver.quit()

我试过这个从每个页面获取链接。

    driver.get("https://www.gharbazar.com/property/search/?_q=&_vt=1&_r=0&_pt=residential&_si=0&_srt=latest")
    page=2
    pagelinks= []
    #links of the 1st page
    links = driver.find_elements_by_xpath("//div[@id = 'search-properties']/a")
    for ele in links:
        pagelinks.append(ele.get_attribute('href'))

    while True:
        nextoption = driver.find_element_by_xpath("//div[@id='pagination-div']//a[contains(text(),'>>')]")
        driver.execute_script("arguments[0].scrollIntoView(true);",nextoption)
        driver.execute_script("window.scrollBy(0,-300)")
        time.sleep(5)
        try:
            driver.find_element_by_link_text(str(page)).click()
            page += 1
            links = driver.find_elements_by_xpath("//div[@id = 'search-properties']/a")
            for ele in links:
                pagelinks.append(ele.get_attribute('href'))
            time.sleep(3)

        except Exception as e:
            print(e)
            break

    print(len(pagelinks))
    for i in range(len(pagelinks)):
        print(pagelinks[i])

    driver.quit()

【讨论】:

  • 最后一页,即 14 页没有被代码抓取,这里也是 nextoption = driver.find_element_by_xpath("//div[@id='pagination-div']//a[contains(text(),'>>')]") 为什么你使用 div 而不是 * 以及 >> 做什么
  • 不确定第 14 页。我使用 'Tag name' 而不是 '*' 只是为了确保指出正确的元素。 '>>' 是链接文本,我正在使用它向下滚动,以便可以看到页码以使其可点击。
  • 上次我看到你有 11 个声望,现在突然 51 个,如何.. 我正在考虑通过 click() 方法单击第 14 页,然后在刮掉第 14 页后将其添加到我创建的 csv 文件中...我尝试使用 try 和 except 但没有显示任何内容
  • 我试图回答其他问题,所以 51。我尝试了下面的代码来编写 CSV 文件。 myfile = open("C:\loginsession\output.csv",'w',newline='') with myfile: writerdata = csv.writer(myfile) for ele in pagelinks: writerdata.writerow([ele])
  • 我已经使用 pandas 将其转换为 csv 文件,但是最后一页没有被抓取仍然是一个谜,所以我决定手动复制 csv 文件中的最后一个链接。你非常有帮助,这就是为什么我要接受你的回答。最后一个问题,为什么这里需要字符串转换:driver.find_element_by_link_text(str(page)).click(),为什么这里的参数为零:driver.execute_script("arguments[0].scrollIntoView(true);",nextoption)
【解决方案2】:

试试这个。

    links = driver.find_elements_by_xpath("//div[@id = 'search-properties']/a")

    for ele in links:
        print(ele.get_attribute('href'))

【讨论】:

  • 感谢您的努力,但它没有处理我主要关心的分页部分......如果我的问题难以理解或含糊不清,请告诉我......我愿意澄清或编辑
猜你喜欢
  • 2016-11-18
  • 1970-01-01
  • 2021-02-11
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-26
  • 1970-01-01
相关资源
最近更新 更多