【问题标题】:Problem while checking internal links with BeautifulSoup and Selenium使用 BeautifulSoup 和 Selenium 检查内部链接时出现问题
【发布时间】:2021-04-07 15:53:59
【问题描述】:

在这里回答:How to join absolute and relative urls?

我想检查 BeautifulSoup 和 Selenium 的内部链接。

当链接如下:完整的 url 路径时脚本正在运行

<a href="http...." />

当链接如下时脚本不起作用:部分 url 路径

<a href="/internal_link.php" />

我的python脚本:

soup=BeautifulSoup(r,'html5lib')
links=[]
for link in soup.findAll('a'):
    set="True"
    for word in exc:
        if word in str(link.get('href')).lower():
            set="False"
            break
    if set=="True":
        try:
            st = re.search('(\S+)', str(link.get('href')).lower())
            st = st.group(0)
            if site in st: # 2 SCENARIOS HERE
                links.append(st)
        except:
            pass

案例 1:检查所有链接:完整路径

if "http" in st:

案例 2:仅检查内部链接:(站点是当前页面)完整路径

if site in st: 

所以,我正在寻找一种加载链接的方法,即使没有 url 的完整路径

【问题讨论】:

标签: python selenium web-scraping beautifulsoup selenium-chromedriver


【解决方案1】:

可能的例子

from bs4 import BeautifulSoup

html = '''
<a href="/internal_link.php" />
<a href="http://www.example.com/internal_link.php" />
<a href="/internal_link.php" />

'''

exc = ['http']
url = 'http://www.example.com'

soup=BeautifulSoup(html,'html5lib')
links=[]
for link in soup.findAll('a'):
    for word in exc:
        if word not in str(link.get('href')).lower():
            links.append(''.join([url,link['href']])) 
        if url in str(link.get('href')).lower():
            links.append(link['href']) 
links

输出

['http://www.example.com/internal_link.php',
 'http://www.example.com/internal_link.php',
 'http://www.example.com/internal_link.php']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-30
    • 2014-11-08
    • 2016-11-15
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多