我正在用Python编写一个爬虫程序。
给定一个网页,我以下列方式提取Html
内容:
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
但是某些文字组件不出现在Html页面来源中,例如在this page中(重定向到索引,请访问其中一个日期并查看特定邮件)如果您查看页面源代码,您将看到邮件文本没有出现在源代码中,但似乎是由JS加载。
如何以编程方式下载此文本?
答案 0 :(得分:2)
这里最简单的选择是向负责电子邮件搜索的URL发出POST请求并解析JSON结果(提及@recursive,因为他首先提出了这个想法)。使用requests
包的示例:
import requests
data = {
'year': '1999',
'month': '05',
'day': '20',
'locale': 'en-us'
}
response = requests.post('http://jebbushemails.com/api/email.py', data=data)
results = response.json()
for email in results['emails']:
print email['dateCentral'], email['subject']
打印:
1999-05-20T00:48:23-05:00 Re: FW: The Reason Study of Rail Transportation in Hillsborough
1999-05-20T04:07:26-05:00 Escambia County School Board
1999-05-20T06:29:23-05:00 RE: Escambia County School Board
...
1999-05-20T22:56:16-05:00 RE: School Board
1999-05-20T22:56:19-05:00 RE: Emergency Supplemental just passed 64-36
1999-05-20T22:59:32-05:00 RE:
1999-05-20T22:59:33-05:00 RE: (no subject)
这里的另一种方法是让真正的浏览器在selenium
浏览器自动化框架的帮助下处理页面加载的动态javascript部分:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome() # can also be, for example, webdriver.Firefox()
driver.get('http://jebbushemails.com/email/search')
# click 1999-2000
button = driver.find_element_by_xpath('//button[contains(., "1999 – 2000")]')
button.click()
# click 20
cell = driver.find_element_by_xpath('//table[@role="grid"]//span[. = "20"]')
cell.click()
# click Submit
submit = driver.find_element_by_xpath('//button[span[1]/text() = "Submit"]')
submit.click()
# wait for result to appear
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//tr[@analytics-event]")))
# get the results
for row in driver.find_elements_by_xpath('//tr[@analytics-event]'):
date, subject = row.find_elements_by_tag_name('td')
print date.text, subject.text
打印:
6:24:27am Fw: Support Coordination
6:26:18am Last nights meeting
6:52:16am RE: Support Coordination
7:09:54am St. Pete Times article
8:05:35am semis on the interstate
...
6:07:25pm Re: Appointment
6:18:07pm Re: Mayor Hood
8:13:05pm Re: Support Coordination
请注意,此处的浏览器也可以是无头,例如PhantomJS
。并且,如果浏览器没有显示工作 - 您可以启动虚拟,请参阅此处的示例:
答案 1 :(得分:2)
您可以向实际的ajax服务发出请求,而不是尝试使用Web界面。
例如,使用此表单数据向http://jebbushemails.com/api/email.py发布请求将产生80kb易于解析的json。
year:1999
month:05
day:20
locale:en-us
答案 2 :(得分:0)
我不是python专家,但任何函数(如urlopen)只能获取静态HTML,而不是执行它。你需要的是某种实际解析和执行JavaScript的浏览器引擎。 似乎在这里回答:
How to Parse Java-script contains[dynamic] on web-page[html] using Python?