2024-09-30 20:19:09 发布
网友
所以,我有这个:
<h1 class='entry-title'> <a href='http://theurlthatvariesinlengthbasedonwhenirequesthehtml'>theTitleIneedthatvariesinlength</a> </h1>
如何检索URL(不总是相同的)和标题(也不总是相同的)
好吧,只要使用字符串,你就可以
>>> 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"的
h1.entry-title > a
h1
a
class="entry-title"
好吧,只要使用字符串,你就可以
不过,还有其他(更好的)解析HTML的选项
使用HTML解析器分析它,例如使用^{} 它将是:
其中
h1.entry-title > a
是一个CSS selector匹配直接位于h1
元素下的a
元素和class="entry-title"
的相关问题 更多 >
编程相关推荐