因此,我有一个数据检索/输入项目,我想提取网页的某个部分并将其存储在文本文件中。我有一个url的文本文件,程序应该为每个url提取页面的相同部分。
具体地说,该程序在诸如this之类的页面上复制"Legal Authority:“后面的法律法规。如您所见,只列出了一条法规。然而,一些urls看起来也像this,这意味着有多个独立的法规。
我的代码适用于第一类页面:
from sys import argv
from urllib2 import urlopen
script, urlfile, legalfile = argv
input = open(urlfile, "r")
output = open(legalfile, "w")
def get_legal(page):
# this is where Legal Authority: starts in the code
start_link = page.find('Legal Authority:')
start_legal = page.find('">', start_link+1)
end_link = page.find('<', start_legal+1)
legal = page[start_legal+2: end_link]
return legal
for line in input:
pg = urlopen(line).read()
statute = get_legal(pg)
output.write(get_legal(pg))在"legalfile“输出.txt中给出所需的法规名称。但是,它不能复制多个法规名称。我尝试过这样的东西:
def get_legal(page):
# this is where Legal Authority: starts in the code
end_link = ""
legal = ""
start_link = page.find('Legal Authority:')
while (end_link != '</a> '):
start_legal = page.find('">', start_link+1)
end_link = page.find('<', start_legal+1)
end2 = page.find('</a> ', end_link+1)
legal += page[start_legal+2: end_link]
if
break
return legal因为每个法规列表都以'</a> '结尾(检查两个链接的任何一个的源代码),所以我想我可以使用这个事实(将它作为索引的结尾)来遍历并收集一个字符串中的所有法规。有什么想法吗?
发布于 2012-07-14 17:18:23
我建议使用BeautifulSoup来解析和搜索您的html。这将比执行基本的字符串搜索容易得多。
下面是一个示例,它提取在包含<b>Legal Authority:</b>标记的<td>标记中找到的所有<a>标记。(请注意,我在这里使用requests库来获取页面内容-这只是一个推荐的、非常容易使用的urlopen替代方法。)
import requests
from BeautifulSoup import BeautifulSoup
# fetch the content of the page with requests library
url = "http://www.reginfo.gov/public/do/eAgendaViewRule?pubId=200210&RIN=1205-AB16"
response = requests.get(url)
# parse the html
html = BeautifulSoup(response.content)
# find all the <a> tags
a_tags = html.findAll('a', attrs={'class': 'pageSubNavTxt'})
def fetch_parent_tag(tags):
# fetch the parent <td> tag of the first <a> tag
# whose "previous sibling" is the <b>Legal Authority:</b> tag.
for tag in tags:
sibling = tag.findPreviousSibling()
if not sibling:
continue
if sibling.getText() == 'Legal Authority:':
return tag.findParent()
# now, just find all the child <a> tags of the parent.
# i.e. finding the parent of one child, find all the children
parent_tag = fetch_parent_tag(a_tags)
tags_you_want = parent_tag.findAll('a')
for tag in tags_you_want:
print 'statute: ' + tag.getText()如果这不是您需要做的,BeautifulSoup仍然是您可能想要用来筛选html的工具。
发布于 2012-07-21 05:15:35
他们在那里提供XML数据,参见my comment。如果您认为无法下载那么多文件(或者另一端可能不喜欢这么多HTTP GET请求),我建议您询问他们的管理员是否愿意为您提供一种不同的数据访问方式。
我在过去已经做了两次(使用科学数据库)。在一种情况下,数据集的巨大规模阻止了下载;他们运行了我的SQL查询并通过电子邮件发送了结果(但之前提出邮寄DVD或硬盘)。在另一种情况下,我可以向were服务发出数百万个HTTP请求(它们还可以),每个请求获取大约1k字节。这将花费很长时间,并且非常不方便(需要一些错误处理,因为其中一些请求总是超时)(并且由于paging而不是原子的)。我收到了一张DVD。
我想,管理和预算办公室可能也会有类似的安排。
https://stackoverflow.com/questions/11480284
复制相似问题