作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 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/
我正在使用 python selenium 捕获源代码 elem = browser.find_element_by_xpath("//*") source_code = elem.get_attri
我是一名优秀的程序员,十分优秀!