我想在这个网站(http://fahrplan.sbb.ch/bin/query.exe/en)上的表单中输入我的起点和终点(O和D),然后将结果写入csv文件。自动化这个任务是我唯一的选择,因为要输入的位置接近1000个。使用下面我从here修改的代码,我可以在表单中输入条目位置,并用br.response().read()
将结果打印到屏幕上。但是,结果是以html格式打印的,但是我希望在下面的图像中用蓝色突出显示的部分导出到csv文件中。我怎么能做到呢?在
图片:
我的代码:
from mechanize import Browser
br = Browser()
# Ignore robots.txt
br.set_handle_robots( False )
# Google demands a user-agent that isn't a robot
br.addheaders = [('User-agent', 'Chrome')]
# Retrieve the Google home page, saving the response
br.open('http://fahrplan.sbb.ch/bin/query.exe/en')
# # Show the available forms
# counter = 0
# for f in br.forms():
# counter += 1
# print f, counter
# print 'counter', counter
# Enter the text inpur
br.select_form(nr=6)
br.form[ "REQ0JourneyStopsS0G" ] = 'Leverkusen Mitte'
br.form[ "REQ0JourneyStopsZ0G" ] = 'Pescara Centrale'
# Get the search results
br.submit()
print br.response().read()
# How can I export the result to csv???
如另一个答案所述,您可以使用HTML解析器(如
BeautifulSoup
)解析响应,选择所需的每个值,将它们放入逗号分隔的字符串中,然后将其写入文件。在下面的示例代码可以让您更好地理解:
如果您在Google的Chrome源代码控制台中查看结果HTML页面的源代码,您将找到四个结果。以下是第一个结果的出发部分截图:
您可以通过使用mycapture中用黄色突出显示的文本搜索控制台来获得剩余的结果。现在您只需要使用
Beautiful Soup
来刮取和切片这个HTML代码,然后将切片的部分保存到CSV
文件中。在相关问题 更多 >
编程相关推荐