【发布时间】:2020-05-19 20:23:14
【问题描述】:
我正在尝试向 URL 发送 AJAX 请求,它成功地返回了我想要抓取的内容。但是,当我尝试实际提取 HTML 的特定部分时,它总是返回 None 或者如果我尝试 find_all 它返回一个空列表。
这是我的代码:
import requests
from bs4 import BeautifulSoup
#AJAX URL to send the post to
url = "https://www.qualitycheck.org/ajax/QualityReport/ajax.aspx"
#Information being requested and BSNID vars (can be extended for additional information like GetAccreditationPrograms)
TJC_ID = '21'
payload = 'f=GetDemographicInfo&bsnid=' + TJC_ID
#Content Headers
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
#Post to TJC
response = requests.request("POST", url, headers = headers, data = payload)
#Clean up the response
soup = BeautifulSoup(response.text, 'lxml')
#testing something
# tryastring = soup.find_all(string="head")
# print(tryastring)
# Pull out the "head-loc" div class only
final = soup.find('div', class_="head-loc")
print(final)
#Print results to make sure it works
# print(final.prettyify())
# print(soup.prettify())
如果您取消注释 # print(final.prettyify()),您将看到它没有返回任何内容。但是,如果您运行print(soup.prettify()),您将获得 HTML 并可以在其中看到该 div 类。
我尝试了很多不同的方法,但我开始认为我的问题不在于我要寻找的地方。关于如何让这个只有带有“head-loc”类的div的任何想法?我实际上想同时提取 head-name 和 head-loc 但我可以在跨过这座桥后弄清楚那部分。
我也尝试过使用 html.parser 而不是 lxml,但这是同一个故事。
【问题讨论】:
-
其实应该有soup.find('div', class_=r'\"head-loc\"')
-
我试过了,但没有用。最终是因为它返回的消息是 JSON,而不是 HTML。所以我必须先解析它,然后才能解析 HTML。
标签: python beautifulsoup