Python:使用 BeautifulSoup 获取 href 的 URL 时遇到问题
Python: trouble getting URL of href using BeautifulSoup
我正在学习如何首先使用 BeautifulSoup 在 Python 中进行网络抓取。我遇到了一些我不确定如何解决的问题,我将向您展示我的代码片段:
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'))
第一行打印的结果是包含公司信息的 table 的 header 之后的第一行(在 link 中您会看到)。第二个结果只是获取 href 字段,用于包含更多信息的 pop-up 页面,我将在此处粘贴:
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 中是否有可以帮助我获取此命令的命令?或者我可以与 BeautifulSoup 结合使用的另一个 Python 模块,以便捕获 pop-up 的 URL?我不想使用正则表达式来获取它。
在此先感谢您的帮助。
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
在幕后几乎每个提取文本模式的包都使用正则表达式,我会建议你使用正则表达式:
https?:[^\s,'[\]();]+
我正在学习如何首先使用 BeautifulSoup 在 Python 中进行网络抓取。我遇到了一些我不确定如何解决的问题,我将向您展示我的代码片段:
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'))
第一行打印的结果是包含公司信息的 table 的 header 之后的第一行(在 link 中您会看到)。第二个结果只是获取 href 字段,用于包含更多信息的 pop-up 页面,我将在此处粘贴:
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 中是否有可以帮助我获取此命令的命令?或者我可以与 BeautifulSoup 结合使用的另一个 Python 模块,以便捕获 pop-up 的 URL?我不想使用正则表达式来获取它。
在此先感谢您的帮助。
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
在幕后几乎每个提取文本模式的包都使用正则表达式,我会建议你使用正则表达式:
https?:[^\s,'[\]();]+