【问题标题】:Python: trouble getting URL of href using BeautifulSoupPython:使用 BeautifulSoup 获取 href 的 URL 时遇到问题
【发布时间】:2021-02-17 11:41:40
【问题描述】:

我正在学习如何首先使用 BeautifulSoup 在 Python 中进行网页抓取。我遇到了一个不知道如何解决的问题,我将向您展示我的代码的这个 sn-p:

from bs4 import BeautifulSoup
import requests

start_url = "https://www1.interactivebrokers.com/en/index.php?f=2222&exch=nasdaq&showcategories=STK#productbuffer"

# Download the HTML from start_url:
downloaded_html = requests.get(start_url)

# Parse the HTML with BeautifulSoup and create a soup object
soup = BeautifulSoup(downloaded_html.text)
# Select table where the data is:
rawTable = soup.select('table.table.table-striped.table-bordered tbody')[2]
url = rawTable.find_all('a',{'class':'linkexternal'})
print(url[0])
print(url[0].get('href'))

第一行打印的结果是包含公司信息的表格标题之后的第一行(在链接中您会看到)。第二个结果只是获取 href 字段,这意味着用于包含更多信息的弹出页面,我将在此处粘贴:

javascript:NewWindow('https://contract.ibkr.info/index.php?action=Details&site=GEN&conid=48811132','Details','600','600','custom','front' );

实际的 URL,当我手动点击它时看起来像这样:

https://contract.ibkr.info/v3.10/index.php?action=Details&site=GEN&conid=48811132

BeautifulSoup 中是否有一个命令可以帮助我得到这个?或者我可以将另一个 Python 模块与 BeautifulSoup 结合以捕获弹出窗口的 URL?我不想使用正则表达式来得到这个。

提前感谢您的帮助。

【问题讨论】:

    标签: python html beautifulsoup href


    【解决方案1】:
    print(url[0].get('href').split("'")[1])
    

    例如

    href = "javascript:NewWindow('https://contract.ibkr.info/index.php?action=Details&site=GEN&conid=48811132','Details','600','600','custom','front');"
    print(href.split("'")[1])
    

    输出

    https://contract.ibkr.info/index.php?action=Details&site=GEN&conid=48811132
    

    【讨论】:

    • 非常感谢@buran!
    【解决方案2】:

    在幕后,几乎每个提取文本模式的包都使用正则表达式,我建议你使用正则表达式:

    https?:[^\s,'[\]();]+

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-11
      • 2018-03-01
      • 2013-09-27
      相关资源
      最近更新 更多