如何创建一个Python脚本从一个网站抓取文本并重新发布到另一个网站?

3 投票
3 回答
666 浏览
提问于 2025-04-16 18:14

我想写一个Python脚本,从这个网站抓取圆周率的数字:http://www.piday.org/million.php,然后把这些数字发布到另一个网站:http://www.freelove-forum.com/index.php。我并不是在发垃圾信息或者开玩笑,这其实是我和网站管理员之间的一个内部玩笑,算是迟到的圆周率日庆祝活动。

3 个回答

0

你可以使用 urllib2 这个模块,它在任何Python的安装包里都有。

这个模块让你可以像打开电脑里的文件一样打开一个网址。所以你可以用它来获取PI的数据,方法是:

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

然后你可以解析得到的文件,这个文件就是你在浏览器里看到的网页的HTML代码。

接下来,你需要使用正确的网址来通过PI发送数据。

1

当你发布一个帖子时,是通过一个叫做 POST 的请求发送到服务器的。看看你网站上的代码:

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

你将发送一个 POST 请求,里面有一个叫 post 的参数(我觉得这个命名不太好),这个参数就是你的文本内容。

至于你要抓取的网站,如果你查看源代码,会发现 Pi 实际上是在一个 <iframe> 里面,网址是:

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

查看 那个 源代码,你会看到页面只有一个 <p> 标签,直接从 <body> 标签下来的(这个网站没有 <!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 地址。

1

导入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'就是你想要找到的标签,它能帮助你定位到π的位置。

指定你想要打印出来的内容

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

然后你可以使用Python自带的文件操作,将这些内容写入一个HTML文件。

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

接着,你可以通过你的网络服务器来提供这个'file.html'文件。

如果你不想使用BeautifulSoup,也可以用re和urllib,但效果没有BeautifulSoup那么好看。

撰写回答