Python BeautifulSoup提取特定的URL

Zer*_*ero 7 python beautifulsoup web-scraping python-2.7

是否可以只获取特定的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>
Run Code Online (Sandbox Code Playgroud)

输出应该只是来自的URL http://www.iwashere.com/

比如输出网址:

http://www.iwashere.com/washere.html
http://www.iwashere.com/wasnot.html
Run Code Online (Sandbox Code Playgroud)

我是通过字符串逻辑完成的.有没有使用BeautifulSoup的直接方法?

Mar*_*ers 14

您可以匹配多个方面,包括使用正则表达式作为属性值:

import re
soup.find_all('a', href=re.compile('http://www\.iwashere\.com/'))
Run Code Online (Sandbox Code Playgroud)

哪个匹配(例如):

[<a href="http://www.iwashere.com/washere.html">next</a>, <a href="http://www.iwashere.com/wasnot.html">next</a>]
Run Code Online (Sandbox Code Playgroud)

所以任何<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
Run Code Online (Sandbox Code Playgroud)

要匹配所有相对路径,请使用负前瞻断言来测试值是否以schem(例如http:mailto:)或双斜杠(//hostname/path)开头; 任何此类值都必须是相对路径:

soup.find_all('a', href=re.compile(r'^(?!(?:[a-zA-Z][a-zA-Z0-9+.-]*:|//))'))
Run Code Online (Sandbox Code Playgroud)


Dro*_*ans 5

如果您使用的是BeautifulSoup 4.0.0或更高版本:

soup.select('a[href^="http://www.iwashere.com/"]')
Run Code Online (Sandbox Code Playgroud)