【发布时间】:2020-09-24 16:48:58
【问题描述】:
我正在使用 BeautifulSoup 并尝试打印所有仅包含公司网站 url 的标签 href。但我的代码也在选择其他href。总共有 71 个公司的网站链接,但我的代码没有选择所有这些 href。 这是我从中提取数据的source
这是我的代码
import requests
import pandas as pd
from bs4 import BeautifulSoup
url = 'https://www.constructionplacements.com/top-construction-companies-in-india-2020/'
name_data = []
website_data = []
print(url)
soup = BeautifulSoup(requests.get(url).content, 'html.parser')
# Loop to select and print all companies title
for h in soup.select('h4'):
print(h.text)
name_data.append(h.text)
# Loop to select and print all companies website url
for w in soup.select('p em a'):
print(w['href'])
website_data.append(w['href'])
df = pd.DataFrame({
'Company Title': name_data,
'Website': website_data
})
print(df)
df.to_csv('ata.csv')
【问题讨论】:
-
这和 Pandas 有什么关系?请仅包含相关标签。
-
@noah 我正在使用 panda 将其保存为 csv 格式
-
请将您的问题表述为MRE。如果您需要编辑以添加包含 Pandas 的代码,那么它必须与您的问题无关。添加 Pandas 信息只会让您更难获得答案,因为这个问题现在有额外的、不必要的复杂性。
-
@noah 你是对的。谢谢你,下次我会确保使用更多相关的标签:-)
标签: python python-3.x list web-scraping beautifulsoup