如何创建一个 Python 脚本,从一个站点抓取文本并将其重新发布到另一个站点



我想创建一个 Python 脚本,从这个站点抓取 Pi 的数字:http://www.piday.org/million.php并将它们重新发布到本网站:http://www.freelove-forum.com/index.php我不是在发送垃圾邮件或恶作剧,这是与创作者和网站管理员的内部笑话,如果您愿意的话,这是一个迟来的 Pi 日庆祝活动。

导入 urllib2 和 BeautifulSoup

import urllib2
from BeautifulSoup import BeautifulSoup

指定网址并使用 urllib2 获取

url = 'http://www.piday.org/million.php'
response = urlopen(url)

然后使用BeautifulSoup,它使用页面中的标签来构建字典,然后您可以使用定义数据的相关标签查询字典以提取所需的内容。

soup = BeautifulSoup(response)
pi = soup.findAll('TAG')

其中"TAG"是您要查找的相关标签,用于标识 pi 的位置。

指定要打印的内容

out = '<html><body>'+pi+'</html></body>

然后,您可以使用 python 内置文件操作将其写入您提供的 HTML 文件。

f = open('file.html', 'w')
f.write(out)
f.close()

然后,您可以使用网络服务器提供文件"file.html"。

如果你不想使用BeautifulSoup,你可以使用re和urllib,但它不像BeautifulSoup那么"漂亮"。

当您发布帖子时,它会通过发送到服务器的POST请求来完成。查看您网站上的代码:

<form action="enter.php" method="post">
  <textarea name="post">Enter text here</textarea> 
</form>

您将发送一个参数为 post(错误对象命名 IMO)的 POST 请求,这是您的文本。

至于你从中抓取的网站,如果你看一下源代码,Pi实际上在一个<iframe>里面有这个URL:

 http://www.piday.org/includes/pi_to_1million_digits_v2.html

查看源代码,您可以看到该页面只是一个直接从<body>标签下降的单个<p>标签(该网站没有<!DOCTYPE>,但我会包括一个):

<!DOCTYPE html>
<html>
  <head>
    ...
  </head>
  <body>
    <p>3.1415926535897932384...</p>
  </body>
</html>

由于 HTML 是 XML 的一种形式,因此您需要使用 XML 解析器来解析网页。我使用BeautifulSoup,因为它可以很好地处理格式错误或无效的XML,但对于完全有效的HTML则更好。

要下载实际页面(您将输入XML解析器),您可以使用Python的内置urllib2。对于POST请求,我会使用 Python 的标准httplib

所以一个完整的例子是这样的:

import urllib, httplib
from BeautifulSoup import BeautifulSoup
# Downloads and parses the webpage with Pi
page = urllib.urlopen('http://www.piday.org/includes/pi_to_1million_digits_v2.html')
soup = BeautifulSoup(page)
# Extracts the Pi. There's only one <p> tag, so just select the first one
pi_list = soup.findAll('p')[0].contents
pi = ''.join(str(s).replace('n', '') for s in pi_list).replace('<br />', '')
# Creates the POST request's body. Still bad object naming on the creator's part...
parameters = urllib.urlencode({'post':      pi, 
                               'name':      'spammer',
                               'post_type': 'confession',
                               'school':    'all'})
# Crafts the POST request's header.
headers = {'Content-type': 'application/x-www-form-urlencoded',
           'Accept':       'text/plain'}
# Creates the connection to the website
connection = httplib.HTTPConnection('freelove-forum.com:80')
connection.request('POST', '/enter.php', parameters, headers)
# Sends it out and gets the response
response = connection.getresponse()
print response.status, response.reason
# Finishes the connections
data = response.read()
connection.close()

但是,如果您将其用于恶意目的,请知道服务器会记录所有 IP 地址。

您可以使用任何Python发行版中的urllib2模块。

它允许您在文件系统上打开文件时打开 URL。因此,您可以使用

pi_million_file = urllib2.urlopen("http://www.piday.org/million.php")

解析生成的文件,该文件将成为您在浏览器中看到的网页的 HTML 代码。

然后,您应该使用正确的URL为您的网站使用PI发布。

最新更新