gpt4 book ai didi

Python SeleniumExtract href 包含特定字符串

转载 作者:行者123 更新时间:2023-12-01 04:03:28 25 4
gpt4 key购买 nike

我正在使用 python selenium 捕获源代码

elem = browser.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")

我需要从源代码中提取包含诸如果酱、蜂蜜、巧克力之类的关键字的元素,然后打印到名为recipes.txt的文件

/items/John-string-jam-string.html

这些是 href 值的格式示例

<a href="/items/John-string-jam-string.html"
<a href="/items/Paul-string-string-jam-string.html"
<a href="/items/string-Mary-honey-string.html"
<a href="/items/choc-string-string.html"

还有许多其他<a href =/items/其中不包含我不想要的关键字的引用。

我是 python 和 selenium 的新手,但我喜欢挑战。预先感谢您的帮助。

最佳答案

有多种方法可以解决这个问题。例如,使用 XPath 定位器和 contains() :

links = browser.find_elements_by_xpath("//a[contains(@href, 'jam') or contains(@href, 'honey') or contains(@href, 'choc')]")

或者,使用 CSS 选择器和 *= 表示法:

links = browser.find_elements_by_css_selector("a[href*=jam],a[href*=honey],a[href*=choc]")
<小时/>

如果您不想在表达式内“硬编码”搜索词值,您可以动态构建定位器:

words = ["jam", "honey", "choc"]
condition = " or ".join("contains(@href, '%s')" % word for word in words)
links = browser.find_elements_by_xpath("//a[%s]" % condition)
<小时/>

要提取/打印出实际的 href 属性值,请使用 .get_attribute() :

for link in links:
print(link.get_attribute("href"))

关于Python SeleniumExtract href 包含特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36101644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com