【发布时间】:2021-01-12 21:57:31
【问题描述】:
我使用美丽的汤来创建一个数据框来抓取数据。但是,有两个问题。
- 为什么 for 循环会运行 2 次?
- 如何去掉数据框上的括号?
导入 urllib.request 作为请求
from bs4 import BeautifulSoup
import bs4
import requests
import pandas as pd
url = "https://finance.yahoo.com/quote/BF-B/profile?p=BF-B"
root = requests.get(url)
soup = BeautifulSoup(root.text, 'html.parser')
records = []
for result in soup:
name = soup.find_all('h1', attrs={'D(ib) Fz(18px)'})
website = soup.find_all('a')[44]
sector = soup.find_all('span')[35]
industry = soup.find_all('span')[37]
records.append((name, website, sector, industry))
df = pd.DataFrame(records, columns=['name', 'website', 'sector', 'industry'])
df.head()
结果如下:
【问题讨论】:
-
您是否针对循环问题进行了任何调试?括号有什么用?请参阅How to Ask、help center。此外,除非绝对必要,否则请不要将信息作为图像共享。请参阅:meta.stackoverflow.com/questions/303812/…、idownvotedbecau.se/imageofcode、idownvotedbecau.se/imageofanexception。
标签: python pandas dataframe beautifulsoup