Beautifulsoup抓取数据,其中有js文本在中间
Beautifulsoup scraping data where there a js text in the middle
我正试图从下面提供的页面中抓取大量数据,当我在浏览器上检查时,我会看到一条路径,但当我使用BeautifulSoup时,我无法获取这些数据。例如,我正在寻找下面这条路的城市北京,但我会得到一个"无"。当我打印汤时,我可以看到html的格式非常不同(我相信js),而beautifulsoup无法处理它,那么我可以从该部分提取数据。谢谢
from bs4 import BeautifulSoup,Tag
import urllib2
hdr = {'Accept': 'text/html,application/xhtml+xml,*/*',"user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"}
url='https://www.upwork.com/freelancers/_~013dfabae39ba01678/'
req=urllib2.Request(url,headers=hdr)
html = urllib2.urlopen(req)
soup=BeautifulSoup(html,"lxml")
#when I inspect I see a path as follows, however printing the soup shows a txt/javascript..
locality=soup.find('span',{'itemprop':'locality'})
在beautifulsoup输出的中间,您可以在var phpVars:的这个snippit中找到所有感兴趣的数据
<script type="text/javascript">
// global Applet object
var Applet = new function() {
var basePath = '/freelancers';
var phpVars = {"urchinId":"UA-62227314-1","csrfTokenCookieName":"XSRF-TOKEN","csrfTokenHeaderName":"X-Odesk-Csrf-Token","runtime_id":"0128305700c7dc55bb8","clientStatsDMetrics":true,"smfAjax":false,"userId":"424358860525125632","isVisitor":true,
你可以试试这个:
from bs4 import BeautifulSoup
import urllib2
import re
import json
hdr = {'Accept': 'text/html,application/xhtml+xml,*/*',"user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"}
url='https://www.upwork.com/freelancers/_~013dfabae39ba01678/'
req=urllib2.Request(url,headers=hdr)
html = urllib2.urlopen(req)
soup=BeautifulSoup(html,"lxml")
script = soup.title.find_next('script').get_text()
map_search = re.search('.*var phpVars = ('{.*);', script)
mapData = map_search.group(1)
mapDataObj = json.loads(mapData)
print mapDataObj['profile']['profile']['location']['city']
它在title
之后首先搜索script
并提取内容。
您感兴趣的数据是json格式的,我们必须使用正则表达式从该脚本中提取json部分,并使用python json
模块进行解析。
您最终可以通过名为mapDataObj
的dict访问数据。
相关文章:
- Angular JS-文本框未在独立范围内更新
- 如何使用注入Firefox控制台的js文本来更改网站的背景图像-示例提供
- 如何从该文本的 onclick 方法中更改 d3.js 文本输入
- PHP/JS 文本差异
- Fabric.js文本转换不起作用
- 为什么可以't我得到了这个d3.js文本的边界框
- Beautifulsoup抓取数据,其中有js文本在中间
- angular js文本到语音转换api
- Chart.js文本颜色
- 正在将Fabric.js文本转换为路径
- 从列表中滚动的 Js 文本大小有限
- JS文本解析器不起作用
- JS- 文本区域行到 javascript 数组
- D3 中的 html.js文本标记
- 时刻.js文本格式和类
- require.js文本插件在文件名中添加“.js”
- JS 文本到 PHP 的数组
- js 文本文件的大小是否是其中的字符数加上一个
- 如何在预填充字段时清除iOS占位符JS文本
- D3.js文本输入(在svg中)将不透明度0转换为1 won't结束于1