我想创建一个Python脚本,从这个网站:http://www.piday.org/million.php获取Pi的数字,并将它们转发到这个网站:http://www.freelove-forum.com/index.php我不是在发送垃圾邮件或玩恶作剧,这是一个与创建者和网站管理员的内部笑话,一个迟来的Pi日庆祝活动,如果你愿意的话。
发布于 2011-05-24 20:07:30
导入urllib2和BeautifulSoup
import urllib2
from BeautifulSoup import BeautifulSoup使用urllib2指定url和获取
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>然后,您可以使用pythons内置文件操作将其写入您提供的HTML文件。
f = open('file.html', 'w')
f.write(out)
f.close()然后使用您的You服务器提供文件'file.html‘。
如果你不想使用BeautifulSoup,你可以使用re和urllib,但是它不像BeautifulSoup那么“漂亮”。
发布于 2011-05-25 04:40:30
当您发布post时,它是通过发送到服务器的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就更好了。
要下载实际的页面,可以使用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地址。
发布于 2011-05-24 20:05:31
您可以使用任何Python发行版中提供的urllib2模块。
它允许您在打开文件系统上的文件时打开URL。因此,您可以使用以下命令获取PI数据
pi_million_file = urllib2.urlopen("http://www.piday.org/million.php")解析生成的文件,它将是您在浏览器中看到的网页的HTML代码。
然后,您应该使用正确的URL为您的网站与PI发布。
https://stackoverflow.com/questions/6109897
复制相似问题