python怎么用css选择器定位href
时间: 2023-09-13 20:10:29 浏览: 37
对于 Python,可以使用 BeautifulSoup 库解析 HTML 页面,使用 CSS 选择器定位 href,示例如下:
```python
from bs4 import BeautifulSoup
# HTML 页面
html_doc = """
<html>
<head>
<title>Example Page</title>
</head>
<body>
<a href="https://www.example.com">链接1</a>
<a href="https://www.example.com/demo">链接2</a>
<a>无href的a标签</a>
</body>
</html>
"""
# 解析 HTML 页面
soup = BeautifulSoup(html_doc, 'html.parser')
# 定位 href
links = soup.select('a[href]')
# 输出 href
for link in links:
print(link['href'])
```
该代码会输出页面中所有有 href 属性的 a 标签的 href 值。
相关问题
python parsel css选择器
Parsel 是一个基于 Selectors 语法的 CSS 选择器库,可以用于在 Python 中解析 HTML 和 XML 文档。Parsel 提供了一种类似于 jQuery 的方式来查询文档,使用 CSS 选择器来查找元素。
以下是使用 Parsel 进行 CSS 选择器的基本示例:
```python
from parsel import Selector
html = """
<html>
<body>
<div class="post">
<h2 class="title"><a href="#">Title 1</a></h2>
<p class="content">Content 1</p>
</div>
<div class="post">
<h2 class="title"><a href="#">Title 2</a></h2>
<p class="content">Content 2</p>
</div>
</body>
</html>
"""
selector = Selector(text=html)
# 使用 CSS 选择器查找元素
titles = selector.css(".post .title a::text").getall()
contents = selector.css(".post .content::text").getall()
print(titles)
print(contents)
```
输出结果为:
```
['Title 1', 'Title 2']
['Content 1', 'Content 2']
```
在上面的示例中,我们使用 `Selector` 类将 HTML 文本转换为 `Selector` 对象。然后,我们使用 `css` 方法来对文档进行查询。在这个例子中,我们使用 CSS 选择器 `.post .title a::text` 查询所有文章标题,使用 `.post .content::text` 查询所有文章内容。最后,我们使用 `getall` 方法获取所有匹配的元素的文本内容。
python request爬虫css选择器
可以使用BeautifulSoup库中的select方法来使用CSS选择器进行爬取,示例代码如下:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 使用CSS选择器获取所有a标签的href属性
links = [a['href'] for a in soup.select('a')]
print(links)
```
注意:在实际使用中,需要根据具体的网页结构来编写CSS选择器。