【问题标题】:How can I get the a tag inside a li using selenium如何使用 selenium 在 li 中获取 a 标签
【发布时间】:2021-09-24 12:46:27
【问题描述】:

我正在编写一个程序来从网站中提取数据以减轻我在公司的工作我需要在“li”标签中获取所有“a”标签的内容我尝试通过 xpath 查找所有元素但它没有产生结果这是我的代码和输出:

def getLinks(link):
    driver.get(link)
    for i in range(0,10):
        result = driver.find_elements_by_xpath(f"/html/body/div[3]/div/div[1]/div[2]/div[3]/ul/li[{i}]/a")
        for r in result:
            print(r.text)
    # for result in results:
    # print(r)

    driver.close()

输出应如下所示:

http://turkosb.com/presmetal-otomotiv.html
    for all li elements

但我得到的是:

   Presmetal Otomotiv Yan San. A.Ş.
    Belirtilmemiş
    +90 224 484 30 30



ps: driver.find_elements_by_xpath(f"/html/body/div[3]/div/div[1]/div[2]/div[3]/ul/li[{i}]/a") this code refers to variable xpath's of all a elements inside li elements

【问题讨论】:

  • 请勿发布代码图片。相反,从 HTML 检查器中复制 HTML,edit 您的问题并将代码格式化为代码块。
  • 对不起,我认为截图会更容易理解
  • 屏幕截图中的代码难以阅读,并且无法复制并粘贴到答案中。像我这样的人经常在浏览器中 Ctrl + 来增加字体大小(怪老头)。放大后图像变得粗糙且难以阅读。

标签: python html selenium


【解决方案1】:

您想要href 属性,但尝试返回元素文本的r.text

使用get_attribute() 获取所有a 标签中的href

并尝试如下所示的相对 xpath。 (根据屏幕截图)

//ul[@class='box-listing']/li/a
options = driver.find_elements_by_xpath("//ul[@class='box-listing']/li/a") # Xpath to find all the `a` tags.
for option in options:
    print(option.get_attribute("href"))

【讨论】:

    猜你喜欢
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2016-08-12
    • 1970-01-01
    相关资源
    最近更新 更多