【问题标题】:Scraping Schema with Beautiful Soup?用美丽的汤刮模式?
【发布时间】:2017-07-29 13:02:18
【问题描述】:

我正在尝试抓取包含以下 html 代码的网站:

 <div class="content-sidebar-wrap"><main class="content"><article 
 class="post-773 post type-post status-publish format-standard has-post-
 thumbnail category-money entry" itemscope 
 itemtype="http://schema.org/CreativeWork">

这包含我感兴趣的数据...我尝试使用 BeautifulSoup 对其进行解析,但返回如下:

 <div class="content-sidebar-wrap"><main class="content"><article 
 class="entry">
 <h1 class="entry-title">Not found, error 404</h1><div class="entry-content
 "><p>"The page you are looking for no longer exists. Perhaps you can return 
 back to the site's "<a href="http://www.totalsportek.com/">homepage</a> and 
 see if you can find what you are looking for. Or, you can try finding it
 by using the search form below.</p><form 
 action="http://www.totalsportek.com/" class="search-form" 
 itemprop="potentialAction" itemscope="" 
 itemtype="http://schema.org/SearchAction" method="get" role="search">

 # I've made small modifications to make it readable

漂亮的汤元素不包含我想要的代码。我对html不太熟悉,但我假设这会调用一些返回数据的外部服务..?我读过这与 Schema 有关。

无论如何我可以访问这些数据吗?

【问题讨论】:

  • 你想从 HTML 代码中得到什么?
  • 一个 html 表格。尝试直接解析表返回 None
  • 嗯,我还是不明白,您想从哪个网站获取信息?如果信息是由 JavaScript 构建的,requests 将不起作用。

标签: python html beautifulsoup schema


【解决方案1】:

您需要在发出请求时指定User-Agent 标头。打印文章标题和内容的工作示例:

import requests
from bs4 import BeautifulSoup

url = "http://www.totalsportek.com/money/barcelona-player-salaries/"

response = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36"})
soup = BeautifulSoup(response.content, "html.parser")

article = soup.select_one(".content article.post.entry.status-publish")
header = article.header.get_text(strip=True)
content = article.select_one(".entry-content").get_text(strip=True)

print(header)
print(content)

【讨论】:

  • 您的代码有效。但是,我在自己的代码中指定了您的用户代理,但它仍然无法正常工作。除了设置用户代理之外还必须做其他事情吗?运行一个简单的 soup.table 不会返回任何应该至少有一张桌子的地方。
  • 另外,我更喜欢直接访问 html 表格,而不是将其解析为文本
  • 拿到桌子了....我就用你的代码。如果可能的话,我想知道为什么 soup.find 不起作用
猜你喜欢
  • 2021-01-15
  • 2014-05-28
  • 2020-12-13
  • 2019-03-13
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多