一直用xpath提取網頁數據,有些文章嵌入一些圖片 a標簽等,一般的通用做法是用【正則】去除,可是也很難滿足要求,
尤其是要提取的內容跟圖片和a標簽在相同的標簽里

如上圖,都在p標簽里,不管是內容還是圖片,這時用正則也不是很靈活,現在辦法是通過提取到文章主體部分,然后依次遍歷每個段落,
div_list = []
div = response.xpath(
'//div[@id="articlebody"]/*[not(name()="style") and not(@class="instrumentName") and not(@id="botlist")]').getall()
if not div:
# articleContent
div = response.xpath(
'//div[@class="articleContent"]/*[not(name()="h4") and not(name()="div")]').getall()
if div and len(div) > 0:
for dv in div:
if "</a>" not in dv or "<img" not in dv:
div_list.append(dv)
div_html = '''<div class="cont-cont">{0} </div>'''.format(
"".join(div_list))
這里只提取p標簽和h3標簽,遍歷后如果內容中含有圖片和a標簽則刪除,這樣就可以處理排除掉特定子元素
