是否可以只获取特定的 URL?
喜欢:
<a href="http://www.iwashere.com/washere.html">next</a>
<span class="class">...</span>
<a href="http://www.heelo.com/hello.html">next</a>
<span class="class">...</span>
<a href="http://www.iwashere.com/wasnot.html">next</a>
<span class="class">...</span>
输出应该只是来自 http://www.iwashere.com/
例如,输出 URL:
http://www.iwashere.com/washere.html
http://www.iwashere.com/wasnot.html
我是用字符串逻辑做的。 BeautifulSoup有什么直接的方法吗?
最佳答案
您可以匹配多个方面,包括对属性值使用正则表达式:
import re
soup.find_all('a', href=re.compile('http://www\.iwashere\.com/'))
哪个匹配(对于你的例子):
[<a href="http://www.iwashere.com/washere.html">next</a>, <a href="http://www.iwashere.com/wasnot.html">next</a>]
所以任何<a>
带有 href
的标签具有以字符串 http://www.iwashere.com/
开头的值的属性.
您可以遍历结果并只挑选出 href
属性:
>>> for elem in soup.find_all('a', href=re.compile('http://www\.iwashere\.com/')):
... print elem['href']
...
http://www.iwashere.com/washere.html
http://www.iwashere.com/wasnot.html
要改为匹配所有相对路径,请使用否定前瞻断言来测试该值是否不以架构(例如 http:
或 mailto:
)或双斜杠开头( //hostname/path
);任何这样的值必须改为相对路径:
soup.find_all('a', href=re.compile(r'^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'))
关于Python BeautifulSoup 提取特定的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15313250/