【发布时间】:2014-10-29 07:33:39
【问题描述】:
我在 html 中有以下代码
<section>
<section>
<h2>Title1</h2>
<p>Text1</p>
<p>Text1</p>
</section>
<section>
<h2>Title2</h2>
<p>Text2</p>
<p>Text2</p>
</section>
<section>
<h2>Title3</h2>
<p>Text3</p>
<p>Text3</p>
</section>
</section>
<section>
<h2>Title2-1</h2>
<p>Text2-1</p>
<p>Text2-1</p>
</section>
<section>
<h2>Title3-1</h2>
<p>Text3-1</p>
<p>Text3-1</p>
</section>
class RUSpider(BaseSpider):
name = "ru"
allowed_domains = ["http://127.0.0.1:8000/"]
start_urls = [
"http://127.0.0.1:8000/week2/1_am/#/",
"http://127.0.0.1:8000/week1/1/",
"http://127.0.0.1:8000/week3/1_am/"
]
rules = [
Rule(SgmlLinkExtractor(), follow=True)
]
def parse(self, response):
filename = response.url.split("/")[3]
hxs = HtmlXPathSelector(response)
divs = hxs.select('//div')
sections = divs.select('//section').extract()
# print sections.extract
#class definition for scrapy and html selector
for each in sections: #iterate over loop [above sections]
soup = BeautifulSoup(each)
sp= soup.prettify()
elements = soup.findAll("section".split())
print len(elements),'sublength'
if len(elements ) > 1:
for element in elements:
for subelement in element:
print subelement,'element'
else:
item = RItem() # create Index Item
item['html_content'] = each
print each
yield item
一些结果的格式正确,尽管一些没有小节的部分被分解成单独的元素。
我想要单独的每个部分。我的意思是因为 1 部分有其他部分。我想遍历这些部分并单独获取它们,以便我可以跟踪循环。由于某些部分没有子部分,因此无需遍历它们。
在 BeautifulSoup 中有没有更好的方法来做到这一点? 我想要以下输出
<section>
<h2>Title1</h2>
<p>Text1</p>
<p>Text1</p>
</section>
<section>
<h2>Title2</h2>
<p>Text2</p>
<p>Text2</p>
</section>
<section>
<h2>Title3</h2>
<p>Text3</p>
<p>Text3</p>
</section>
<section>
<h2>Title2-1</h2>
<p>Text2-1</p>
<p>Text2-1</p>
</section>
<section>
<h2>Title3-1</h2>
<p>Text3-1</p>
<p>Text3-1</p>
</section>
【问题讨论】:
-
您只想获取包含
h2、p标签的section?each这里的类型是什么?是bs4.element.Tag类型的对象吗?你是怎么得到sections的? -
不,我希望每个部分都是单独的。我的意思是因为 1 部分有其他部分。我想遍历这些部分并单独获取它们所以我可以跟踪循环。由于某些部分没有子部分,因此无需循环遍历它们。
-
尽量减少您的问题,以便其他人可以重现它。并清楚地说明你真正想要什么。
-
检查解决方案,如果对您有帮助,请告诉我。
标签: python html django-views beautifulsoup scrapy-spider