【问题标题】:Web scraping using python example使用 python 示例进行网页抓取
【发布时间】:2012-10-19 17:10:05
【问题描述】:

谁能给我看一下代码,比如说每 30 分钟从 google 获取一次Recent News,然后使用 python 在我的网站上展示它们?

我观看了 44 个视频教程并学习了基础知识。

一个例子是:

import urllib2
from BeautifulSoup import BeautifulSoup
# or if your're using BeautifulSoup4:
# from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.timeanddate.com/worldclock/astronomy.html?n=78').read())

for row in soup('table', {'class' : 'spad'})[0].tbody('tr'):
  tds = row('td')
  print tds[0].string, tds[1].string
  # will print date and sunrise

但是像我这样的初学者无法理解这段代码如何帮助我解决上面的例子。

【问题讨论】:

  • 如果你想显示新闻,你应该使用google rss feed。你不需要网络抓取任何东西,除非你只是为了练习。 example
  • 这只是一个例子...我想获得新闻但不是来自 google..

标签: python web-scraping


【解决方案1】:

这是一个简单的例子,它每半小时从谷歌新闻中获取所有主要标题并将它们打印出来。至于在您的网站上显示它们取决于它的实施方式。例如,如果它从 MYSQL 数据库中获取内容,您可以轻松地使此脚本在每次下载新标题时更新数据库。

import mechanize
import cookielib
import lxml.html as lh
import time  

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

while True:
    r = br.open('https://news.google.com/')
    html = r.read()
    doc=lh.fromstring(html)
    for i in doc.xpath('.//*[@class="esc-lead-article-title"]'):
        print i.text_content()
    time.sleep(1800)

【讨论】:

  • 但是root,您如何获得文章的来源和标题?我试过esc-lead-article-source,但没用。
【解决方案2】:

每当您看到不熟悉的东西的导入声明时,快速进行谷歌搜索总是明智的。我的产量了

BeautifulSoup 。在这里,您可以阅读名为 beautiful soup 的 python 库的文档。

UrlLib2 这里是用来打开 URL 的库

阅读文档,它应该可以帮助您了解如何使用这个小 sn-p 来发挥您的优势 :)。

【讨论】:

  • 我可以理解这段代码...我知道...但是我不想打印它,而是想将它添加到我的网站上...我可以使用 python 来做到这一点吗?而且我知道我应该运行程序来执行代码......所以我需要每 30 分钟执行一次程序?
  • 找到一个允许您发布动态网站的库,或者,使用 websockets。是的,您可以使用 python 执行此操作,不,您不需要每 30 分钟执行一次,您可以让它继续运行,然后检查时间何时在 30 分钟或 00 标记上。祝你好运!
  • @Loclip -- 请根据您的评论编辑您的问题,您的问题有些混乱。告诉我们到底是什么困扰着您?您是否无法收集您想要的数据,为什么?您无法显示它吗?为什么?
猜你喜欢
  • 2011-10-21
  • 1970-01-01
  • 2020-10-04
  • 2021-05-08
  • 2018-07-20
  • 2021-01-13
  • 2020-03-13
  • 2016-02-10
相关资源
最近更新 更多