我要不使用xpath方法找到一个href属性中包含sbuuid的a标签
时间: 2024-06-09 07:11:20 浏览: 11
可以使用以下代码来实现:
```python
from lxml import etree
# 构造示例HTML
html = '''
<html>
<body>
<a href="http://example.com/sbuuid123">Link 1</a>
<a href="http://example.com/someotherlink">Link 2</a>
<a href="http://example.com/sbuuid456">Link 3</a>
</body>
</html>
'''
# 将HTML解析为Element对象
root = etree.HTML(html)
# 使用xpath方法找到a标签中href属性包含'sbuuid'的元素
links = root.xpath("//a[contains(@href, 'sbuuid')]")
# 打印结果
for link in links:
print(link.attrib['href'])
```
输出结果为:
```
http://example.com/sbuuid123
http://example.com/sbuuid456
```
相关问题
python xpath获取a标签href
你可以使用Python的lxml库来解析HTML并使用XPath定位a标签的href属性。下面是一个简单的示例代码:
```python
from lxml import etree
# 用lxml解析HTML
html = etree.parse('your_html_file.html')
# 使用XPath定位所有的a标签
a_tags = html.xpath('//a')
# 遍历所有a标签并获取href属性
for a in a_tags:
href = a.get('href')
print(href)
```
这段代码首先使用lxml库解析HTML文件,然后使用XPath定位所有的a标签。接着,通过遍历每个a标签并使用`get()`方法获取其href属性值,并打印出来。
你可以将`your_html_file.html`替换为你要解析的HTML文件路径,或者将其替换为HTML内容字符串,然后使用`etree.fromstring(html_content)`来解析HTML内容。
selenium爬虫获取html中ul标签下所有a标签的href属性
要获取HTML中`ul`标签下所有`a`标签的`href`属性,可以使用Selenium的`find_elements_by_xpath()`方法和`get_attribute()`方法。以下是一个例子:
```python
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://example.com")
# 找到ul标签
ul = driver.find_element_by_xpath("//ul")
# 找到所有a标签
links = ul.find_elements_by_xpath(".//a")
# 循环遍历所有a标签,获取href属性
for link in links:
href = link.get_attribute("href")
print(href)
# 关闭浏览器
driver.quit()
```
在上面的代码中,我们首先使用`find_element_by_xpath()`方法找到`ul`标签,然后使用`.//a`语法查找所有子孙节点中的`a`标签。接着,使用`find_elements_by_xpath()`方法获取所有`a`标签,然后循环遍历每个标签,使用`get_attribute()`方法获取`href`属性的值,并打印输出。最后使用`quit()`方法关闭浏览器。
需要注意的是,如果要查找的`ul`标签和`a`标签具有特定的类名或ID,可以在XPath表达式中添加`@class`或`@id`属性,以缩小查找范围。例如,`//ul[@class='menu']//a`表示查找`class`属性为`menu`的`ul`标签下的所有`a`标签。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)