Beautiful Soup:在 url 之后的锚点处提取文本

Beautiful Soup: Extract text at the a anchor after url

我有一些 html,其中 href 中的 URL 出现在页面上出现的标题之前。我正在尝试获取该标题和 url 并将其提取到数据框中。以下代码是我目前所拥有的。

import requests
from bs4 import BeautifulSoup

url = 'https://patentsview.org/download/data-download-tables'
page = requests.get(url)

soup = BeautifulSoup(page.content, "html.parser")

results = soup.find_all("div", class_="file-title")
print(results)

pd.DataFrame([a.text for a in soup.select('.file-title a')], columns=['Title'])

就目前而言,我只有一列我希望结果采用以下格式:

Title URL
application URL1
assignee URL2
... ...

我在 Real Python 上关注了这个页面,但我已经停滞不前了,因为我似乎无法将他们的下一部分转化为我的需求。

如果对此有任何帮助,那就太好了。预先感谢您的帮助。

编辑 1:我对原始问题进行了一些编辑。我想扩展它以在第二列中也包含标题所附加的 URL。我还合并了第一个答案中提供的代码。

只需在每个 <div> 中的 <a> 上调用 .text 即可打印您的信息:

for e in soup.find_all("div", class_="file-title"):
    print(e.a.text)

css selector:

for a in soup.select('.file-title a'):
    print(a.text)

例子

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = 'https://patentsview.org/download/data-download-tables'
page = requests.get(url)

soup = BeautifulSoup(page.content, "html.parser")

for e in soup.find_all("div", class_="file-title"):
    print(e.a.text)
输出
application
assignee
botanic
cpc_current
cpc_group
cpc_subgroup
cpc_subsection
figures
...

DataFrame

pd.DataFrame([a.text for a in soup.select('.file-title a')], columns=['Title'])
输出:
Title
application
assignee
botanic
cpc_current
cpc_group
cpc_subgroup
cpc_subsection
figures
foreigncitation
foreign_priority
government_interest
government_organization
inventor
ipcr
lawyer
location
mainclass
mainclass_current

编辑

根据评论获得“标题”和“Url”

data = []
for a in soup.select('.file-title a'):
    data.append({
        'Title':a.text,
        'Url':a['href']
    })
pd.DataFrame(data)