selenium爬虫获取html中标签中属性
时间: 2024-03-25 13:41:26 浏览: 31
要获取HTML标签中的属性,可以使用Selenium中的`get_attribute()`方法。例如,如果要获取一个链接标签`<a>`中的`href`属性,可以使用以下代码:
```python
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://example.com")
link = driver.find_element_by_tag_name("a")
href = link.get_attribute("href")
print(href)
```
在上面的代码中,首先使用`find_element_by_tag_name()`方法获取第一个`<a>`标签,然后使用`get_attribute()`方法获取该标签的`href`属性。打印输出这个属性的值。
你可以根据你要获取的属性类型,将标签名和属性名替换为你需要的值。
相关问题
selenium爬虫点击html中标签中属性
要在Selenium中模拟点击HTML标签中的属性,需要先找到该元素,然后使用`get_attribute()`方法获取属性值,最后使用`execute_script()`方法执行JavaScript代码模拟点击。
以下是一个简单的例子,演示如何在Chrome浏览器中使用Selenium模拟点击一个链接标签`<a>`中的`href`属性:
```python
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://example.com")
# 找到链接元素
link = driver.find_element_by_tag_name("a")
# 获取链接的href属性
href = link.get_attribute("href")
# 使用JavaScript模拟点击链接
driver.execute_script("window.location.href = arguments[0];", href)
# 关闭浏览器
driver.quit()
```
在上面的代码中,首先使用`find_element_by_tag_name()`方法找到第一个`<a>`标签,然后使用`get_attribute()`方法获取该标签的`href`属性。接着,使用`execute_script()`方法执行一段JavaScript代码,模拟点击链接的行为。最后使用`quit()`方法关闭浏览器。
需要注意的是,如果链接的`href`属性是javascript代码,我们需要使用`execute_script()`方法直接执行该代码,而不是跳转到该链接。
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)