python - 如何使用python在网站中查找反向链接

标签 python regex beautifulsoup

<分区>

我有点被这种情况困住了,我想找到网站的反向链接,我找不到怎么做,这是我的正则表达式:

readh = BeautifulSoup(urllib.urlopen("http://www.google.com/").read()).findAll("a",href=re.compile("^http"))

我想做的是查找反向链接,查找以 http 开头的链接而不是包含 google 的链接,我不知道如何管理它?

最佳答案

from BeautifulSoup import BeautifulSoup
import re

html = """
<div>hello</div>
<a href="/index.html">Not this one</a>"
<a href="http://google.com">Link 1</a>
<a href="http:/amazon.com">Link 2</a>
"""

def processor(tag):
    href = tag.get('href')
    if not href: return False
    return True if (href.find("google") == -1) else False

soup = BeautifulSoup(html)
back_links = soup.findAll(processor, href=re.compile(r"^http"))
print back_links

--output:--
[<a href="http:/amazon.com">Link 2</a>]

但是,获取所有以 http 开头的链接,然后在这些链接中搜索 hrefs 中没有“google”的链接可能更有效:

http_links = soup.findAll('a', href=re.compile(r"^http"))
results = [a for a in http_links if a['href'].find('google') == -1]
print results

--output:--
[<a href="http:/amazon.com">Link 2</a>]

关于python - 如何使用python在网站中查找反向链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18234298/

相关文章:

python - file.write() 还是打印到文件更好?

python - <br> 标签用漂亮的汤和 python 搞砸了我的数据

python - 使用Python使用网站的搜索功能

python - 抓取动态元素

python - Pandas 在对行进行操作后重置索引

python - Python打开<del>命名管道</del>字符设备专用文件进行读写的方法

c# - 正则表达式 - 文件名中的版本

php - 正则表达式从正则表达式代码中排除 1 个单词

c# - 在 C# 正则表达式中是否有等同于\Q ...\E

python - Web 抓取表可以正确读取错误数据