Python BeautifulSoup - 在 iframe 中抓取 Web 内容

Fra*_*nkC 3 python beautifulsoup web-scraping

我们有这个网址:https : //www.aliexpress.com/store/feedback-score/1665279.html

所需的内容是 iframe 内的“反馈历史记录”表:

Feedback    1 Month 3 Months    6 Months
Positive (4-5 Stars)    154 562 1,550
Neutral (3 Stars)   8   19  65
Negative (1-2 Stars)    8   20  57
Positive feedback rate  95.1%   96.6%   96.5%
Run Code Online (Sandbox Code Playgroud)

我们如何提取它?

cod*_*ody 8

您只需要获取 的src属性iframe,然后请求并解析其内容:

import requests
from bs4 import BeautifulSoup

s = requests.Session()
r = s.get("https://www.aliexpress.com/store/feedback-score/1665279.html")

soup = BeautifulSoup(r.content, "html.parser")
iframe_src = soup.select_one("#detail-displayer").attrs["src"]

r = s.get(f"https:{iframe_src}")

soup = BeautifulSoup(r.content, "html.parser")
for row in soup.select(".history-tb tr"):
    print("\t".join([e.text for e in row.select("th, td")]))
Run Code Online (Sandbox Code Playgroud)

结果:

反馈 1 个月 3 个月 6 个月
正面(4-5 星) 154 562 1,550
中性(3 星) 8 19 65
负(1-2 星) 8 20 57
好评率 95.1% 96.6% 96.5%