㈠ 如何用python提取网页中框架的源代码
简单的做个例子,框架路径可以自己修改,调用像网络等网站时无法读取其中源码,涉及到一些安全问题,所以路径要求是合法的允许访问的路径 function GetFrameInnerHtml(objIFrame) { var iFrameHTML = ""; if (objIFrame.contentDocument) { //针...
㈡ 怎么使用python查看网页源代码
使用python查看网页源代码的方法:
1、使用“import”命令导入requests包
import requests
2、使用该包的get()方法,将要查看的网页链接传递进去,结果赋给变量x
x = requests.get(url='http://www.hao123.com')
3、用“print (x.text)”语句把网页的内容以text的格式输出
print(x.text)
完整代码如下:
执行结果如下:
更多Python知识,请关注:Python自学网!!
㈢ 求python抓网页的代码
python3.x中使用urllib.request模块来抓取网页代码,通过urllib.request.urlopen函数取网页内容,获取的为数据流,通过read()函数把数字读取出来,再把读取的二进制数据通过decode函数解码(编号可以通过查看网页源代码中<meta http-equiv="content-type" content="text/html;charset=gbk" />得知,如下例中为gbk编码。),这样就得到了网页的源代码。
如下例所示,抓取本页代码:
importurllib.request
html=urllib.request.urlopen('
).read().decode('gbk')#注意抓取后要按网页编码进行解码
print(html)
以下为urllib.request.urlopen函数说明:
urllib.request.urlopen(url,
data=None, [timeout, ]*, cafile=None, capath=None,
cadefault=False, context=None)
Open the URL url, which can be either a string or a Request object.
data must be a bytes object specifying additional data to be sent to
the server, or None
if no such data is needed. data may also be an iterable object and in
that case Content-Length value must be specified in the headers. Currently HTTP
requests are the only ones that use data; the HTTP request will be a
POST instead of a GET when the data parameter is provided.
data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.parse.urlencode() function takes a mapping or
sequence of 2-tuples and returns a string in this format. It should be encoded
to bytes before being used as the data parameter. The charset parameter
in Content-Type
header may be used to specify the encoding. If charset parameter is not sent
with the Content-Type header, the server following the HTTP 1.1 recommendation
may assume that the data is encoded in ISO-8859-1 encoding. It is advisable to
use charset parameter with encoding used in Content-Type header with the Request.
urllib.request mole uses HTTP/1.1 and includes Connection:close header
in its HTTP requests.
The optional timeout parameter specifies a timeout in seconds for
blocking operations like the connection attempt (if not specified, the global
default timeout setting will be used). This actually only works for HTTP, HTTPS
and FTP connections.
If context is specified, it must be a ssl.SSLContext instance describing the various SSL
options. See HTTPSConnection for more details.
The optional cafile and capath parameters specify a set of
trusted CA certificates for HTTPS requests. cafile should point to a
single file containing a bundle of CA certificates, whereas capath
should point to a directory of hashed certificate files. More information can be
found in ssl.SSLContext.load_verify_locations().
The cadefault parameter is ignored.
For http and https urls, this function returns a http.client.HTTPResponse object which has the
following HTTPResponse
Objects methods.
For ftp, file, and data urls and requests explicitly handled by legacy URLopener and FancyURLopener classes, this function returns a
urllib.response.addinfourl object which can work as context manager and has methods such as
geturl() — return the URL of the resource retrieved,
commonly used to determine if a redirect was followed
info() — return the meta-information of the page, such
as headers, in the form of an email.message_from_string() instance (see Quick
Reference to HTTP Headers)
getcode() – return the HTTP status code of the response.
Raises URLError on errors.
Note that None
may be returned if no handler handles the request (though the default installed
global OpenerDirector uses UnknownHandler to ensure this never happens).
In addition, if proxy settings are detected (for example, when a *_proxy environment
variable like http_proxy is set), ProxyHandler is default installed and makes sure the
requests are handled through the proxy.
The legacy urllib.urlopen function from Python 2.6 and earlier has
been discontinued; urllib.request.urlopen() corresponds to the old
urllib2.urlopen.
Proxy handling, which was done by passing a dictionary parameter to urllib.urlopen, can be
obtained by using ProxyHandler objects.
Changed in version 3.2: cafile
and capath were added.
Changed in version 3.2: HTTPS virtual
hosts are now supported if possible (that is, if ssl.HAS_SNI is true).
New in version 3.2: data can be
an iterable object.
Changed in version 3.3: cadefault
was added.
Changed in version 3.4.3: context
was added.
㈣ 求助,python 解析爬取的网页源码中的json部分
我用re把json的部分截取出来了,也用json.loads()解析成了字典,现在的问题是里面需要的信息那部分是有一些是unicode 编码的,求解。。。。
{"pageName":"mainsrp","mods":{"shopcombotip":{"status":"hide","export":false},"shopstar":{"status":"hide","export":false},"navtablink":{"status":"hide","export":false},"personalbar":{"status":"show","data":{"metisData":{"nickname":"","query":"秋季打底衫","shopItems":[{"text":"黄钻爱买店铺","count":"500+","url":"/search?q\u003d秋季打底衫\u0026tab\u003dmysearch\u0026filter_rectype\u003d44\u0026stats_click\u003dms_from:44","trace":"metis44"},{"text":"回头客爱买店铺","count":"500+","url":"/search?q\u003d秋季打底衫\u0026tab\u003dmysearch\
㈤ Python怎么爬取证才通这家网站的源码
不知道你是用框架还是用 Selenium 爬的内容, iframe 里的内容实际上就是另一个网页了。
你只是爬它的源码是爬不到的, 你要提取 iframe 里的 src 所指向的网址, 重新打开它, 然后才爬他的源码。 或者如果你用框架, 里面应该有另外提供方法, 读取 iframe 中的内容
㈥ python爬虫怎么获取动态的网页源码
一个月前实习导师布置任务说通过网络爬虫获取深圳市气象局发布的降雨数据,网页如下:
心想,爬虫不太难的,当年跟zjb爬煎蛋网无(mei)聊(zi)图的时候,多么清高。由于接受任务后的一个月考试加作业一大堆,导师也不催,自己也不急。
但是,导师等我一个月都得让我来写意味着这东西得有多难吧。。。今天打开一看的确是这样。网站是基于Ajax写的,数据动态获取,所以无法通过下载源代码然后解析获得。
从某不良少年写的抓取淘宝mm的例子中收到启发,对于这样的情况,一般可以同构自己搭建浏览器实现。phantomJs,CasperJS都是不错的选择。
导师的要求是获取过去一年内深圳每个区每个站点每小时的降雨量,执行该操作需要通过如上图中的历史查询实现,即通过一个时间来查询,而这个时间存放在一个hidden类型的input标签里,当然可以通过js语句将其改为text类型,然后执行send_keys之类的操作。然而,我失败了。时间可以修改设置,可是结果如下图。
为此,仅抓取实时数据。选取python的selenium,模拟搭建浏览器,模拟人为的点击等操作实现数据生成和获取。selenium的一大优点就是能获取网页渲染后的源代码,即执行操作后的源代码。普通的通过 url解析网页的方式只能获取给定的数据,不能实现与用户之间的交互。selenium通过获取渲染后的网页源码,并通过丰富的查找工具,个人认为最好用的就是find_element_by_xpath("xxx"),通过该方式查找到元素后可执行点击、输入等事件,进而向服务器发出请求,获取所需的数据。
[python]view plain
#coding=utf-8
fromtestStringimport*
fromseleniumimportwebdriver
importstring
importos
fromselenium.webdriver.common.keysimportKeys
importtime
importsys
default_encoding='utf-8'
ifsys.getdefaultencoding()!=default_encoding:
reload(sys)
sys.setdefaultencoding(default_encoding)
district_navs=['nav2','nav1','nav3','nav4','nav5','nav6','nav7','nav8','nav9','nav10']
district_names=['福田区','罗湖区','南山区','盐田区','宝安区','龙岗区','光明新区','坪山新区','龙华新区','大鹏新区']
flag=1
while(flag>0):
driver=webdriver.Chrome()
driver.get("hianCe/")
#选择降雨量
driver.find_element_by_xpath("//span[@id='fenqu_H24R']").click()
filename=time.strftime("%Y%m%d%H%M",time.localtime(time.time()))+'.txt'
#创建文件
output_file=open(filename,'w')
#选择行政区
foriinrange(len(district_navs)):
driver.find_element_by_xpath("//div[@id='"+district_navs[i]+"']").click()
#printdriver.page_source
timeElem=driver.find_element_by_id("time_shikuang")
#输出时间和站点名
output_file.write(timeElem.text+',')
output_file.write(district_names[i]+',')
elems=driver.find_elements_by_xpath("//span[@onmouseover='javscript:changeTextOver(this)']")
#输出每个站点的数据,格式为:站点名,一小时降雨量,当日累积降雨量
foreleminelems:
output_file.write(AMonitorRecord(elem.get_attribute("title"))+',')
output_file.write(' ')
output_file.close()
driver.close()
time.sleep(3600)
[python]view plain
#Encoding=utf-8
defOnlyCharNum(s,oth=''):
s2=s.lower()
fomart=',.'
forcins2:
ifnotcinfomart:
s=s.replace(c,'')
returns
defAMonitorRecord(str):
str=str.split(":")
returnstr[0]+","+OnlyCharNum(str[1])
㈦ python如何抓取网页源代码中的字符串
使用正则匹配,列:
importrequests
importre
req=requests.get(url)
r=re.findall('<scriptsrc="(.*?)"></script>',req.text)#(.*?)非贪婪匹配
print(r)
自己网上找找python正则方面的知识
㈧ python怎么爬取网页源代码
#!/usr/bin/env python3
#-*- coding=utf-8 -*-
import urllib3
if __name__ == '__main__':
http=urllib3.PoolManager()
r=http.request('GET','IP')
print(r.data.decode("gbk"))
可以正常抓取。需要安装urllib3,py版本3.43
㈨ python,求一个简单的selenium+re的网页源码爬取
网页爬取不一定要用Selenium,Selenium是为了注入浏览器获取点击行为的调试工具,如果网页无需人工交互就可以抓取,不建议你使用selenium。要使用它,你需要安装一个工具软件,使用Chrome浏览器需要下载chromedriver.exe到system32下,如使用firefox则要下载geckodriver.exe到system32下。下面以chromedriver驱动chrome为例:
#-*-coding:UTF-8-*-
fromseleniumimportwebdriver
frombs4importBeautifulSoup
importre
importtime
if__name__=='__main__':
options=webdriver.ChromeOptions()
options.add_argument('user-agent="Mozilla/5.0(Linux;Android4.0.4;GalaxyNexusBuild/IMM76B)AppleWebKit/535.19(KHTML,likeGecko)Chrome/18.0.1025.133MobileSafari/535.19"')
driver=webdriver.Chrome()
driver.get('url')#你要抓取网络文库的URL,随便找个几十页的替换掉
html=driver.page_source
bf1=BeautifulSoup(html,'lxml')
result=bf1.find_all(class_='rtcspage')
bf2=BeautifulSoup(str(result[0]),'lxml')
title=bf2.div.div.h1.string
pagenum=bf2.find_all(class_='size')
pagenum=BeautifulSoup(str(pagenum),'lxml').span.string
pagepattern=re.compile('页数:(d+)页')
num=int(pagepattern.findall(pagenum)[0])
print('文章标题:%s'%title)
print('文章页数:%d'%num)
whileTrue:
num=num/5.0
html=driver.page_source
bf1=BeautifulSoup(html,'lxml')
result=bf1.find_all(class_='rtcspage')
foreach_resultinresult:
bf2=BeautifulSoup(str(each_result),'lxml')
texts=bf2.find_all('p')
foreach_textintexts:
main_body=BeautifulSoup(str(each_text),'lxml')
foreachinmain_body.find_all(True):
ifeach.name=='span':
print(each.string.replace('xa0',''),end='')
elifeach.name=='br':
print('')
print(' ')
ifnum>1:
page=driver.find_elements_by_xpath("//div[@class='page']")
driver.execute_script('arguments[0].scrollIntoView();',page[-1])#拖动到可见的元素去
nextpage=driver.find_element_by_xpath("//a[@data-fun='next']")
nextpage.click()
time.sleep(3)
else:
break
执行代码,chromedriver自动为你打开chrome浏览器,此时你翻页到最后,点击阅读更多,然后等一段时间后关闭浏览器,代码继续执行。
㈩ python怎么看源码进行网络爬虫
在我们日常上网浏览网页的时候,经常会看到一些好看的图片,我们就希望把这些图片保存下载,或者用户用来做桌面壁纸,或者用来做设计的素材。
我们最常规的做法就是通过鼠标右键,选择另存为。但有些图片鼠标右键的时候并没有另存为选项,还有办法就通过就是通过截图工具截取下来,但这样就降低图片的清晰度。好吧~!其实你很厉害的,右键查看页面源代码。
我们可以通过python 来实现这样一个简单的爬虫功能,把我们想要的代码爬取到本地。下面就看看如何使用python来实现这样一个功能。
一,获取整个页面数据
首先我们可以先获取要下载图片的整个页面信息。
getjpg.py
#coding=utf-8
import urllib
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
html = getHtml("http://tieba..com/p/2738151262")
print html
Urllib 模块提供了读取web页面数据的接口,我们可以像读取本地文件一样读取www和ftp上的数据。首先,我们定义了一个getHtml()函数:
urllib.urlopen()方法用于打开一个URL地址。
read()方法用于读取URL上的数据,向getHtml()函数传递一个网址,并把整个页面下载下来。执行程序就会把整个网页打印输出。
二,筛选页面中想要的数据
Python 提供了非常强大的正则表达式,我们需要先要了解一点python 正则表达式的知识才行。
http://www.cnblogs.com/fnng/archive/2013/05/20/3089816.html
假如我们网络贴吧找到了几张漂亮的壁纸,通过到前段查看工具。找到了图片的地址,如:src=”https://gss0..com/70cFfyinKgQFm2e88IuM_a/forum......jpg”pic_ext=”jpeg”
修改代码如下:
import re
import urllib
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = re.findall(imgre,html)
return imglist
html = getHtml("http://tieba..com/p/2460150866")
print getImg(html)
我们又创建了getImg()函数,用于在获取的整个页面中筛选需要的图片连接。re模块主要包含了正则表达式:
re.compile() 可以把正则表达式编译成一个正则表达式对象.
re.findall() 方法读取html 中包含 imgre(正则表达式)的数据。
运行脚本将得到整个页面中包含图片的URL地址。
三,将页面筛选的数据保存到本地
把筛选的图片地址通过for循环遍历并保存到本地,代码如下:
#coding=utf-8
import urllib
import re
def getHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext'
imgre = re.compile(reg)
imglist = re.findall(imgre,html)
x = 0
for imgurl in imglist:
urllib.urlretrieve(imgurl,'%s.jpg' % x)
x+=1
html = getHtml("http://tieba..com/p/2460150866")
print getImg(html)
这里的核心是用到了urllib.urlretrieve()方法,直接将远程数据下载到本地。
通过一个for循环对获取的图片连接进行遍历,为了使图片的文件名看上去更规范,对其进行重命名,命名规则通过x变量加1。保存的位置默认为程序的存放目录。
程序运行完成,将在目录下看到下载到本地的文件。