Sam*_*Kim 0 python beautifulsoup
我正在尝试使用 Beautifulsoup Python 从网站上抓取一些数据,但它没有返回它应该返回的值。以下是我的代码。
import requests
from bs4 import BeautifulSoup
url = 'https://finance.naver.com/item/sise.nhn?code=005930'
# send a HTTP request to the URL of the webpage I want to access
r = requests.get(url)
data = r.text
# making the soup
soup = BeautifulSoup(data, 'html.parser')
print(soup.find('iframe', attrs={'title': '?? ??'}))
Run Code Online (Sandbox Code Playgroud)
它返回,
<iframe bottommargin="0" frameborder="0" height="360" marginheight="0" name="day" scrolling="no" src="/item/sise_day.nhn?code=005930" title="?? ??" topmargin="0" width="100%"></iframe>
Run Code Online (Sandbox Code Playgroud)
打印结果中不包含 HTML 标签。但是,如果我查看网页上的开发人员工具,它清楚地显示“iframe”标签中有很多标签。
所以我的问题是,为什么我的代码不返回我从网页上的开发人员工具中看到的“iframe”标签内的所有标签?
我试过查找一些信息,但没有一个给我明确的答案。是因为它是由 javascript 加载的吗?如果是这样,我该如何检查我尝试抓取的网页是否已由 javascript 加载?
最后,如果我想要的数据是由 javascript 加载的,我应该使用什么模块/库来抓取它?
该表在 iframe 内可用。您需要发送对该 iframe url 的请求。您可以使用熊猫来 read_html() 并获取表格。
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://finance.naver.com/item/sise.nhn?code=005930'
# send a HTTP request to the URL of the webpage I want to access
r = requests.get(url)
data = r.text
# making the soup
soup = BeautifulSoup(data, 'html.parser')
newurl="https://finance.naver.com" +soup.find('iframe', attrs={'title': '?? ??'})['src']
dfs=pd.read_html(newurl)
df=dfs[0]
df = df.dropna(how='any',axis=0)
print(df)
Run Code Online (Sandbox Code Playgroud)
输出:
?? ?? ??? ?? ?? ?? ???
1 2019.11.29 50300.0 1000.0 51200.0 51400.0 50200.0 11012292.0
2 2019.11.28 51300.0 900.0 51900.0 52100.0 51300.0 6833885.0
3 2019.11.27 52200.0 400.0 51800.0 52300.0 51600.0 7546261.0
4 2019.11.26 51800.0 0.0 51900.0 52900.0 51800.0 27372226.0
5 2019.11.25 51800.0 200.0 52200.0 52600.0 51700.0 9050625.0
9 2019.11.22 51600.0 600.0 51000.0 51600.0 50900.0 8478310.0
10 2019.11.21 51000.0 1000.0 51600.0 52100.0 50600.0 14298646.0
11 2019.11.20 52000.0 1500.0 53400.0 53400.0 52000.0 12560070.0
12 2019.11.19 53500.0 0.0 53200.0 53500.0 52700.0 8907177.0
13 2019.11.18 53500.0 200.0 53600.0 53800.0 53200.0 7746554.0
Run Code Online (Sandbox Code Playgroud)