Python 从网页中嵌入的javascript中提取特定数据

Python 从网页中嵌入的javascript中提取特定数据,python,regex,web-scraping,lxml,Python,Regex,Web Scraping,Lxml,我只想使用下面给出的方法从链接“”中提取纬度。 纬度在名为“location”的javascript变量中给出。 代码是: from lxml import html import re URL = "http://hdfc.com/branch-locator" var_lat = re.compile('(?<="latitude":).+(?=")') main_page = html.parse(URL).getroot() lat = main_page.xpath("//

我只想使用下面给出的方法从链接“”中提取纬度。 纬度在名为“location”的javascript变量中给出。 代码是:

from lxml import html
import re

URL = "http://hdfc.com/branch-locator"
var_lat = re.compile('(?<="latitude":).+(?=")')

main_page = html.parse(URL).getroot()

lat = main_page.xpath("//script[@type='text/javascript']")[1]

ans = re.search(var_lat,str(lat))

print ans
从lxml导入html
进口稀土
URL=”http://hdfc.com/branch-locator"

var_lat=re.compile(')(?我认为需要一些小的更改

排队

lat = main_page.xpath("//script[@type='text/javascript']")[1] # This should be 10 
线路

ans = re.search(var_lat,str(lat)) 
应该是

ans = re.search(var_lat, lat.text) 
str(lat)
将调用对象
lat
函数,该函数与
lat.text
不同

一般来说,最好先检查所有LAT,然后开始搜索所需字符串。因此,这应该是-

lat = main_page.xpath("//script[@type='text/javascript']")
for l in lat:
    if l.text is None:
        continue
    # print l.text
    ans = re.search(var_lat,(l.text))
    if ans is not None:
        break

print ans

抱歉,已编辑以修复此问题。注意:这可能不是您想要的确切解决方案-但应该为您提供匹配所需正则表达式的第一个实例。您可能需要进一步处理
ans

我下面编写的代码适用于网页中的嵌入式javascript

from lxml import html
from json import dump
import re

dumped_data = []

class theAddress:
    latude = ""

URL = "http://hdfc.com/branch-locator"
var_lat = re.compile('(?<="latitude":").+?(?=")')

main_page = html.parse(URL).getroot()

residue = main_page.xpath("//script[@type='text/javascript']/text()")[1]
all_latude = re.findall(var_lat,residue)

for i in range(len(all_latude)):
    obj = theAddress()
    obj.latude = all_latude[i]

    dumped_data.append(obj.__dict__)

f = open('hdfc_add.json','w')
dump(dumped_data, f, indent = 1)
从lxml导入html
从json导入转储
进口稀土
转储的_数据=[]
类别地址:
latude=“”
URL=”http://hdfc.com/branch-locator"

var_lat=re.compile(“(?不,不工作。它显示此错误:回溯(最近一次调用):文件“hdfcspider.py”,第13行,在ans=re.search(var_lat,l.text)文件“/usr/lib/python2.7/re.py”,第142行,在搜索返回_compile(模式,标志)。搜索(字符串)TypeError:expected string或bufferFixed-error-这不是“最终答案”,只是一种方法,应该可以帮助您解决其余部分。