如何为a href执行Regex?

2024-04-19 22:51:24 发布

您现在位置:Python中文网/ 问答频道 /正文

<div class="user-info" style="position:absolute;top:5px;left:5px;z-index:1">

<a href="/kjrphotography" target="_blank">

<img class="photo_user" src="http://images.ak.instagram.com/profiles/profile_507998691_75sq_1376497436.jpg" width="40" height="40" title="kjrphotography" border="0">

</a>

<span class="usertag" style="display: none;">@kjrphotography</span>

</div>

所以我把它分开了一点,基本上我想找到“用户信息”在哪里,然后我需要获取a href是什么。使用类/kjrspan或用户标记。你知道吗

如果有人能帮我这个忙,我会很感激的。你知道吗

到目前为止,我有这个,但我知道这不是接近正确的

userdata = re.findall(ur"<div class=\"user-info\"><\/div>",curlData)

Tags: 用户divinfotargetindexstyletopposition
2条回答
from lxml import html
xml = html.fragments_fromstring("""<div class="user-info" style="position:absolute;top:5px;left:5px;z-index:1">

<a href="/kjrphotography" target="_blank">

<img class="photo_user" src="http://images.ak.instagram.com/profiles/profile_507998691_75sq_1376497436.jpg" width="40" height="40" title="kjrphotography" border="0">

</a>

<span class="usertag" style="display: none;">@kjrphotography</span>

</div>""")[0]

xml.find('span').text

返回'@kjphotography'

当然最好也最容易使用HTML,而html是您的HTML页面-下面是一个使用BeautifulSoup的示例:

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
print soup.select('.user-info a')[0]['href']
# /kjrphotography

你会发现这比把HTML当作字符串更简单,也更健壮。。。你知道吗

或者:

for info in soup.find_all('div', class_='user-info'):
    print 'href:', info.find('a', href=True)['href']
    print 'user:', info.find('span', class_='usertag').text

#href: /kjrphotography
#user: @kjrphotography

相关问题 更多 >