如何创建一个Python脚本,从一个站点获取文本并将其转发到另一个站点?

2024-04-20 04:54:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个Python脚本,从这个站点获取Pi的位数: http://www.piday.org/million.php 并将其转发到以下站点: http://www.freelove-forum.com/index.php 我不是垃圾邮件或恶作剧,这是一个内部笑话与创造者和网站管理员,一个迟到的Pi日庆祝,如果你愿意。在


Tags: org脚本comhttpindex站点wwwpi
3条回答

导入urllib2和BeautifulSoup

import urllib2
from BeautifulSoup import BeautifulSoup

指定url并使用urllib2获取

^{pr2}$

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

soup = BeautifulSoup(response)

pi = soup.findAll('TAG')

其中“TAG”是您要查找的相关标记,用于标识pi所在的位置。在

指定要打印的内容

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

然后,您可以使用pythons内置的文件操作将其写入所服务的HTML文件。在

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

然后你把文件送过来文件.html'使用您的Web服务器。在

如果你不想使用BeautifulSoup,可以使用re和urllib,但它没有BeautifulSoup那样“漂亮”。在

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

它允许您在打开文件系统上的文件时打开URL。所以你可以用

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

解析结果文件,该文件将是您在浏览器中看到的网页的HTML代码。在

然后你应该使用正确的网址为你的网站张贴与PI。在

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

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

{{IMO>你要发送的是一个名为cd3}的对象。在

至于您要从中获取的站点,如果您查看源代码,则Pi实际上位于一个<iframe>中,该URL为:

^{pr2}$

查看那个源代码,您可以看到该页面只是一个<p>标记,它直接从一个<body>标记下降(该站点没有{},但我将包括一个):

<!DOCTYPE html>

<html>
  <head>
    ...
  </head>

  <body>
    <p>3.1415926535897932384...</p>
  </body>
</html>

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

要下载实际的页面,您可以使用Python内置的^{}将其提供给XML解析器。对于POST请求,我将使用Python的标准^{}。在

一个完整的例子是:

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地址都是恶意的,那你就知道了。在

相关问题 更多 >