Python 美苏不能';t从表中刮取值
我和beautifulsoup在Python上进行了比较。 我可以在我的Chrome浏览器中看到如下html代码,但是如何才能在Python 美苏不能';t从表中刮取值,python,web-scraping,beautifulsoup,python-requests,Python,Web Scraping,Beautifulsoup,Python Requests,我和beautifulsoup在Python上进行了比较。 我可以在我的Chrome浏览器中看到如下html代码,但是如何才能在中获得文本 请告诉我怎样才能把文本放在 更新:我尝试了@Anand S Kumar给我的教程。我编辑的代码是 : 对我来说还是不行。里面的值仍然是:真正的数据是通过Ajax加载的,这就是为什么BeautifulSoup只能获取占位符 要监视ajax请求,您可以使用诸如Chrome developer tools之类的工具。就像在另一个答案中已经说过的那样,页面中的实际
中获得文本
请告诉我怎样才能把文本放在
更新:我尝试了@Anand S Kumar给我的教程。我编辑的代码是 :
对我来说还是不行。里面的值仍然是:真正的数据是通过Ajax加载的,这就是为什么BeautifulSoup只能获取占位符
要监视ajax请求,您可以使用诸如Chrome developer tools之类的工具。就像在另一个答案中已经说过的那样,页面中的实际数据是javascript呈现的/ajax呈现的 如果您在chrome中为页面使用
查看页面源代码
,您将看到正在检查的组件的原始html源代码-
<tbody id="hor-minimalist-tb">
<tr>
<td align="center" style="color:#000000">-</td>
<td align="center">-</td>
<td id="2412_a4" align="center">-</td>
<td id="2412_f4" align="center" style="color:#000000">-</td>
</tr>
<tr>
<td align="center" style="color:#000000">-</td>
<td align="center">-</td>
<td id="2412_a3" align="center">-</td>
<td id="2412_f3" align="center" style="color:#000000">-</td>
</tr>
<tr>
<td align="center" style="color:#000000">-</td>
<td align="center">-</td>
<td id="2412_a2" align="center">-</td>
<td id="2412_f2" align="center" style="color:#000000">-</td>
</tr>
.
.
</tbody>
req.text
包含页面的原始html源代码,而不是javascript呈现的DOM。这就是为什么你会在获得结果的同时从BeautifulSoup获得结果
对于javascript呈现的页面,您可以按照以下教程进行操作-(其中的代码是针对lxml的,但可以轻松地适应BeautifulSoup)。它使用QT Web工具包库。(免责声明:这不是我的教程/内容)在这种情况下,如果数据不在HTML源代码中,它应该来自某个地方。因此,如果您检查站点发布的HTTP连接,您会发现数据是从网站API获取的:
http://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=tse_2412.tw&json=1&delay=0&_=1438929024846
json的示例:
{
"msgArray": [
{
"ts": "0",
"tk0": "2412.tw_tse_20150807_B_9999301124",
"tk1": "2412.tw_tse_20150807_B_9999283564",
"oa": "98.00",
"ob": "97.90",
"tlong": "1438928700000",
"f": "1584_141_122_674_83_",
"ot": "14:25:00",
"ex": "tse",
"g": "22_130_76_108_106_",
"ov": "-",
.
.
.
.
}
但是,当您希望直接访问URL时。您需要使用有效的cookies。但是如果你想
s = requests.Session()
r = s.get("http://mis.twse.com.tw/stock/fibest.jsp?stock=2412")
您将获得
通过检查响应代码,您将发现您需要发送Accept Language
cookies
r = s.get("http://mis.twse.com.tw/stock/fibest.jsp?stock=2412", headers = {"Accept-Language":"en-US,en;q=0.5"})
你是怎么得到这个的@你可以用莴苣,谢谢。但我不明白如何在我的代码中使用它。如何在Python中获取数据?谢谢您的教程。但它不能工作。价值仍然是——我编辑了我的问题并添加了新的代码。这是另一个重复的问题,当数据是JS而不是HTML时,试图刮取数据。
req = requests.get(site, headers = hdr, verify = False)
http://mis.twse.com.tw/stock/api/getStockInfo.jsp?ex_ch=tse_2412.tw&json=1&delay=0&_=1438929024846
{
"msgArray": [
{
"ts": "0",
"tk0": "2412.tw_tse_20150807_B_9999301124",
"tk1": "2412.tw_tse_20150807_B_9999283564",
"oa": "98.00",
"ob": "97.90",
"tlong": "1438928700000",
"f": "1584_141_122_674_83_",
"ot": "14:25:00",
"ex": "tse",
"g": "22_130_76_108_106_",
"ov": "-",
.
.
.
.
}
s = requests.Session()
r = s.get("http://mis.twse.com.tw/stock/fibest.jsp?stock=2412")
r = s.get("http://mis.twse.com.tw/stock/fibest.jsp?stock=2412", headers = {"Accept-Language":"en-US,en;q=0.5"})