【问题标题】:HTML Scraping the website with duplicated div class nameHTML 使用重复的 div 类名抓取网站
【发布时间】:2020-03-10 01:56:30
【问题描述】:

我目前正在处理抓取 baka-update 的 HTML。 但是,Div Class 的名称是重复的。

由于我的目标是 csv 或 json,我想使用 [sCat] 中的信息作为列名,使用 [sContent] 来存储..... 他们是这种网站的方式吗?

谢谢,

示例 https://www.mangaupdates.com/series.html?id=75363

图片 1 图 2

from lxml import html
import requests

page = requests.get('http://www.mangaupdates.com/series.html?id=153558?')
tree = html.fromstring(page.content)

#Get the name of the columns.... I hope
sCat = tree.xpath('//div[@class="sCat"]/text()')
#Get the actual data
sContent = tree.xpath('//div[@class="sContent"]/text()')

print('sCat: ', sCat)
print('sContent: ', sContent)

我试过了,但没有找到 @Jasper Nichol M Fabella

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 首先我尝试使用 sCat 和 sContent 以及我刚刚添加的图片 2。似乎我可能会在 sContent 中获得一些信息,但我无法在 sCat 中获得任何信息
  • 您能否在问题中添加到目前为止您尝试过的代码?
  • 刚刚添加!谢谢

标签: python html parsing html-parsing html-parser


【解决方案1】:

我尝试编辑您的代码并得到以下输出。也许会有所帮助。


from lxml import html
import requests

page = requests.get('http://www.mangaupdates.com/series.html?id=153558?')
tree = html.fromstring(page.content)
# print(page.content)

#Get the name of the columns.... I hope
sCat = tree.xpath('//div[@class="sCat"]')
#Get the actual data
sContent = tree.xpath('//div[@class="sContent"]')

print('sCat: ', len(sCat))
print('sContent: ', len(sContent))
json_dict={}

for i in  range(0,len(sCat)):
#     print(''.join(i.itertext()))
    sCat_text=(''.join(sCat[i].itertext()))
    sContent_text=(''.join(sContent[i].itertext()))
    json_dict[sCat_text]=sContent_text
print(json_dict)


我得到以下输出

希望对你有帮助

【讨论】:

  • 感谢您的帮助,对我很有帮助。
【解决方案2】:

您可以使用xpath 表达式并在要抓取的内容上创建绝对路径

【讨论】:

  • 谢谢。如果它们的名称重复,我应该如何制作绝对路径?
  • 在你的 url 上试试这个。首先检查元素。然后按 Ctrl + F。然后输入 //div[@class='Scat'][1]
  • 我找不到任何东西。
【解决方案3】:

下面是 requestslxml 库的示例:

from lxml import html
import requests

r = requests.get('https://www.mangaupdates.com/series.html?id=75363')
tree = html.fromstring(r.content)

sCat = [i.text_content().strip() for i in tree.xpath('//div[@class="sCat"]')]
sContent = [i.text_content().strip() for i in tree.xpath('//div[@class="sContent"]')]

【讨论】:

  • 很高兴我能帮上忙。
【解决方案4】:

你用什么刮? 如果您使用的是 BeautifulSoup?然后,您可以使用带有类标识符的 FindAll 方法搜索页面上的所有内容,并通过该方法进行迭代。您可以使用特殊的“_class”界定符

类似

import bs4
soup = bs4.BeautifulSoup(html.source)
soup.find_all('div', class_='sCat')
# do rest of your logic work here

编辑:在您进行编辑之前,我在手机上的缓存页面上打字。所以没有看到变化。尽管我看到您正在使用原始 lxml 库进行解析。是的,这更快,但我不太熟悉,因为我只为一个项目使用了原始 lxml 库,但我认为您可以将两种搜索方法链接起来以提取等效的东西。

【讨论】:

  • 感谢您的帮助。由于我在没有背景的情况下进行编码,这对我来说真的很难
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
相关资源
最近更新 更多