BeautifulGroup不解析标题或段落

2024-06-02 07:42:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用requests和BeautifulSoup实现一个web收集。web爬虫程序代码正常工作,但提取部分不工作。唯一写入输出文件的数据是标题行。我在网上看了几十个例子,但还是没能纠正我的问题。我哪里出错了?在

secondSoupParser = BeautifulSoup(raw_html, 'html.parser')
list_of_headers = []

list_of_paras = [] 



try:
    
   results_parser = secondSoupParser.find('div', attrs={'style':'padding-left:10px;width:98%'})

except AttributeError as e:
    
   logging.exception(e)
    
   sys.exit(1)



for div in results_parser.findAll('h2'):
    
   for para in div.findAll('p'):
        
     para_text = para.text.strip()
        
     list_of_paras.append(para_text)
                 
     list_of_headers.append(list_of_paras)

filenameTest = (output_directory + '/'+ 'test' + '-' + timestamp + '.csv')
   
output_file2 = open(filenameTest, 'w', encoding='utf8')



writer2 = csv.writer(output_file2)

writer2.writerow(['Test'])

writer2.writerow(list_of_headers)


更新

目标url格式为:

^{pr2}$

Tags: oftextdivwebparseroutputhtmlresults
1条回答
网友
1楼 · 发布于 2024-06-02 07:42:38

<p>标记不包含在<h2>标记中,因此不需要首先循环<h2>。这应该可以很好地将<p>的文本提取到列表中:

results_parser = secondSoupParser.find('div', attrs={'style': 'padding-left:10px;width:98%'})

for para in results_parser.findAll('p'):
    para_text = para.text.strip()
    list_of_paras.append(para_text)
    list_of_headers.append(list_of_paras)

相关问题 更多 >