【问题标题】:beautifulsoup doesn't show all ellementsbeautifulsoup 没有显示所有元素
【发布时间】:2017-07-24 12:04:02
【问题描述】:

我正在尝试使用 BeautifulSoup.find 解析淘宝网站并获取有关商品的信息(照片、文本和链接),但它没有找到所有类。

url='https://xuanniwen.world.tmall.com/category-1268767539.htm?search=y&catName=%BC%D0%BF%CB#bd&view_op=citations_histogram'

def get_html(url):
    r = requests.get(url)
    return r.text

html=get_html(url)
soup=BeautifulSoup(html, 'lxml')
z=soup.find("div",{"class":"J_TItems"})

z-为空。 但例如:

z=soup.find("div",{"class":"skin-box-bd"})
len(z)
Out[196]: 3

工作正常

为什么这种方法不起作用?我应该怎么做才能获得所有关于好的信息?我正在使用 python 2.7

【问题讨论】:

  • 尝试soup.text.find("J_TItems"),你会看到它会说soup中根本没有J_TItems,我认为正在发生的事情是你要解析的内容不在html中,实际上是由 JavaScript 动态构建的,你应该看看 Python 的 selenium 模块。

标签: python parsing beautifulsoup


【解决方案1】:

所以,看起来您要解析的项目是由 JavaScript 动态构建的,这就是 soup.text.find("J_TItems") 返回 -1 的原因,即文本中根本没有“J_TItems”。您可以将 selenium 与 JS 解释器一起使用,对于无头浏览,您可以像这样使用 PhantomJS

from bs4 import BeautifulSoup
from selenium import webdriver

url='https://xuanniwen.world.tmall.com/category-1268767539.htm?search=y&catName=%BC%D0%BF%CB#bd&view_op=citations_histogram'

browser = webdriver.PhantomJS()
browser.get(url)
html = browser.page_source

soup = BeautifulSoup(html, 'html5lib') # I'd also recommend using html5lib
JTitems = soup.find("div", attrs={"class":"J_TItems"})

注意你想要的项目在<div class="item4line1">定义的每一行内,其中有5个(你可能只想要前三个,因为其他两个不在主搜索中,过滤不应该是困难,一个简单的rows = rows[2:] 就可以了):

rows = JTitems.findAll("div", attrs={"class":"item4line1"})
>>> len(rows)
5

现在请注意,您在问题中提到的每个“好”都在 <dl class="item"> 内,因此您需要将它们全部放在 for 循环中:

Goods = []    
for row in rows:
    for item in row.findAll("dl", attrs={"class":"item"}):
        Goods.append(item)

剩下要做的就是得到你提到的“照片、文字和链接”,这可以很容易地访问Goods列表中的每个项目,通过检查你可以知道如何获取每个信息,例如,对于图片 url,简单的一行是:

>>> Goods[0].find("dt", class_='photo').a.img["src"]
'//img.alicdn.com/bao/uploaded/i3/TB19Fl1SpXXXXbsaXXXXXXXXXXX_!!0-item_pic.jpg_180x180.jpg'

【讨论】:

  • 非常感谢,非常感谢您的帮助。也许你可以告诉我,当我尝试解析网站时,我怎么能理解使用 JavaScript、Ajax 等隐藏内容的方法。
  • @egorkh 很高兴为您提供帮助!我会说去selenium 并加载 JavaScript 始终是最好的选择,但是如果你想要的东西不存在,你可以通过检查你想要抓取的页面的 html 源代码来判断你是否需要它它在检查代码窗口中,你需要 JavaScript 解析!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-11
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多