我正在尝试使用标签抓取主表:
<table _ngcontent-jna-c4="" class="rayanDynamicStatement">
来自使用“BeautifulSoup”库的以下网站,但代码返回空[],而打印 soup 返回 html 字符串且请求状态为 200。我发现当我使用浏览器“检查元素”工具时,我可以看到表格标签但在“查看页面源代码”中,作为“app-root”标签一部分的表标签未显示。 (您会看到 <app-root></app-root>
是空的)。此外,网页组件中没有“json”文件来从中提取数据。请帮助我如何抓取表格数据。
import urllib.request
import pandas as pd
from urllib.parse import unquote
from bs4 import BeautifulSoup
yurl='https://www.codal.ir/Reports/Decision.aspx?LetterSerial=T1hETjlDjOQQQaQQQfaL0Mb7uucg%3D%3D&rt=0&let=6&ct=0&ft=-1&sheetId=0'
req=urllib.request.urlopen(yurl)
print(req.status)
#get response
response = req.read()
html = response.decode("utf-8")
#make html readable
soup = BeautifulSoup(html, features="html")
table_body=soup.find_all("table")
print(table_body)
最佳答案
该表位于源 HTML
但有点隐藏然后由 JavaScript
渲染。它位于 <script>
之一标签。可以通过 bs4
找到它然后用 regex
解析。最后可以将表数据转储到 json.loads
然后到pandas
并发送至.csv
文件,但由于我不懂波斯语,所以你必须看看它是否有任何用处。
仅通过查看一些值,我认为是的。
哦,这可以无需来完成selenium
.
方法如下:
import pandas as pd
import json
import re
import requests
from bs4 import BeautifulSoup
url = "https://www.codal.ir/Reports/Decision.aspx?LetterSerial=T1hETjlDjOQQQaQQQfaL0Mb7uucg%3D%3D&rt=0&let=6&ct=0&ft=-1&sheetId=0"
scripts = BeautifulSoup(
requests.get(url, verify=False).content,
"lxml",
).find_all("script", {"type": "text/javascript"})
table_data = json.loads(
re.search(r"var datasource = ({.*})", scripts[-5].string).group(1),
)
pd.DataFrame(
table_data["sheets"][0]["tables"][0]["cells"],
).to_csv("huge_table.csv", index=False)
这会输出一个巨大的文件,如下所示:
关于python - 从网站结果中抓取表格为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66753132/