python - 使用 Beautiful Soup + Requests 时 find_all() 未找到任何结果

标签 python web-scraping beautifulsoup html-parsing python-requests

我正在第一次尝试使用 BeautifulSoup 和 Requests,并尝试通过从新闻网站抓取一些信息来学习。该项目的目标是能够从终端读取新闻摘要,因此我需要有效地抓取和解析文章标题和文章正文文本。

我仍处于获取标题的阶段,但当我尝试使用 find_all() 函数时,我根本没有存储任何数据。下面是我的代码:

from bs4 import BeautifulSoup
from time import strftime
import requests

date = strftime("%Y/%m/%d")

url = "http://www.thedailybeast.com/cheat-sheets/" + date + "/cheat-sheet.html"

result = requests.get(url)
c = result.content
soup = BeautifulSoup(c, "lxml")

titles = soup.find_all('h1 class="title multiline"')

print titles

有什么想法吗?如果有人还有任何建议/提示来改进我目前所拥有的或我正在采取的方法,我一直在寻求变得更好,所以请告诉我!

干杯

最佳答案

您将此处的所有内容都放在引号中:

titles = soup.find_all('h1 class="title multiline"')

这使得 BeautifulSoup 搜索 h1 class="title multiline" 元素。

相反,使用:

titles = soup.find_all("h1", class_="title multiline")

或者,使用 CSS selector :

titles = soup.select("h1.title.multiline")

实际上,由于页面的动态特性,要获取所有标题,您必须采用不同的方法:

import json

results = json.loads(soup.find('div', {'data-pageraillist': True})['data-pageraillist'])
for result in results:
    print result["title"]

打印:

Hillary Email ‘Born Classified’
North Korean Internet Goes Down
Kid-Porn Cops Go to Gene Simmons’s Home
Baylor Player Convicted of Rape After Coverup
U.S. Calls In Aussie Wildfire Experts
Markets’ 2015 Gains Wiped Out
Black Lives Matters Unveils Platform
Sheriff Won’t Push Jenner Crash Charge 
Tear Gas Used on Migrants Near Macedonia
Franzen Considered Adopting Iraqi Orphan

关于python - 使用 Beautiful Soup + Requests 时 find_all() 未找到任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32143622/

相关文章:

python - 如何提取和忽略标记中的跨度? - Python

python - 如何从 NFL 赛程表中抓取所有 td 和 tr 数据

python - 我如何在 Django 中编写此查询? (约会时间)

Pythonplotnine增加刻度线之间的距离

python - 在Linux服务器中使用Scrapy Crawlera时,连接被对方​​拒绝: 111: Connection refused.

python - 在没有打印日志的情况下运行 scrapy runspider

python - 使用 beautifulsoup python 抓取 span 类 HTML 中的值

Python argparse 断言错误

python - 显式访问 Python 的内置范围

python - Instagram API : getting the user id of all the users who have liked a post