python如何获取网页script里的url?

Python019

python如何获取网页script里的url?,第1张

获取方法如下:

def get_js_value(url):

page_source = requests.get(url, headers=headers).content.decode('utf8')

selector = etree.HTML(page_source)

script_content = selector.xpath('/html/head/script[3]/text()')[0]

context = js2py.EvalJs()

context.execute(script_content)

今天简单使用了一下python的re模块和lxml模块,分别利用的它们提供的正则表达式和xpath来解析页面源码从中提取所需的title,xpath在完成这样的小任务上效率非常好,在这里之所以又使用了一下正则表达式是因为xpath在处理一些特殊的页面的时候会出现乱码的情况,当然这不是xpath的原因,而是页面本身编码,跟utf-8转码之间有冲突所致,这里看代码

python抽取指定url页面的title方法(python获取当前页面的url) python 抽取 url title 脚本之家 第1张

# !/usr/bin/python

#-*-coding:utf-8-*-

'''

功能:抽取指定url的页面内容中的title

'''

import re

import chardet

import urllib

from lxml import etree

def utf8_transfer(strs):

'''

utf8编码转换

'''

try:

if isinstance(strs, unicode):

strs = strs.encode('utf-8')

elif chardet.detect(strs)['encoding'] == 'GB2312':

strs = strs.decode("gb2312", 'ignore').encode('utf-8')

elif chardet.detect(strs)['encoding'] == 'utf-8':

strs = strs.decode('utf-8', 'ignore').encode('utf-8')

except Exception, e:

print 'utf8_transfer error', strs, e

return strs

def get_title_xpath(Html):

'''

用xpath抽取网页Title

'''

Html = utf8_transfer(Html)

Html_encoding = chardet.detect(Html)['encoding']

page = etree.HTML(Html, parser=etree.HTMLParser(encoding=Html_encoding

可将很多url放在一个列表中,然后用循环语句遍历。代码如下:

urls=[url1,url2,url3]

for u in urls:

requests.get(u)

txt=r.text