我在和Python搏斗。我知道某个标题的类别。我需要通用<a href。。。在这个h1

2024-09-30 20:19:09 发布

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

所以,我有这个:

<h1 class='entry-title'>
    <a href='http://theurlthatvariesinlengthbasedonwhenirequesthehtml'>theTitleIneedthatvariesinlength</a>
</h1>

如何检索URL(不总是相同的)和标题(也不总是相同的)


Tags: httpurl标题titleh1classhrefentry
2条回答

好吧,只要使用字符串,你就可以

>>> s = '''<h1 class='entry-title'>
...     <a href='http://theurlthatvariesinlengthbasedonwhenirequesthehtml'>theTitleIneedthatvariesinlength</a>
... </h1>'''
>>> s.split('>')[1].strip().split('=')[1].strip("'")
'http://theurlthatvariesinlengthbasedonwhenirequesthehtml'
>>> s.split('>')[2][:-3]
'theTitleIneedthatvariesinlength'

不过,还有其他(更好的)解析HTML的选项

使用HTML解析器分析它,例如使用^{}它将是:

from bs4 import BeautifulSoup

data = "your HTML here"  # data can be the result of urllib2.urlopen(url)

soup = BeautifulSoup(data)
link = soup.select("h1.entry-title > a")[0]

print link.get("href")
print link.get_text()

其中h1.entry-title > a是一个CSS selector匹配直接位于h1元素下的a元素和class="entry-title"

相关问题 更多 >