Beautifulsoup抓取数据,其中有js文本在中间

Beautifulsoup scraping data where there a js text in the middle

本文关键字:js 文本 在中间 抓取 数据 Beautifulsoup      更新时间:2023-12-16

我正试图从下面提供的页面中抓取大量数据,当我在浏览器上检查时,我会看到一条路径,但当我使用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访问数据。