python爬虫bs4中用select如何获取属性值


from bs4 import BeautifulSoup

html = """
<html><head><title>The Dormouse's story</title></head>

<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html,'lxml')

我想获取a标签下,href的值,或者获取 id和class 的值,怎么操作呢,请教!



```python
from bs4 import BeautifulSoup
import re
html = """
<html><head><title>The Dormouse's story</title></head>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html, 'lxml')
code_url = re.findall('<a class="(.*?)"\shref="(.*?)"\sid="(.*?)">.*?</a>',str(soup), re.S)
print(code_url)


[('sister', 'http://example.com/elsie', 'link1'), ('sister', 'http://example.com/lacie', 'link2'), ('sister', 'http://example.com/tillie', 'link3')]

```

imgs=soup.select('a')
url=imgs[1]['href']
print(url)