鱼C论坛

 找回密码
 立即注册
查看: 2928|回复: 4

[已解决]爬虫问题求助

[复制链接]
发表于 2022-4-15 18:10:32 | 显示全部楼层    本楼为最佳答案   
本帖最后由 isdkz 于 2022-4-16 08:23 编辑

第一个问题:

你可以继续对 tip 标签的内容使用 BeautifulSoup 解析

第二个问题:

想打印的更整齐一点可以使用 prettytable 这个库,使用之前先执行以下命令安装。
  1. pip install prettytable -i https://mirrors.aliyun.com/pypi/simple
复制代码


对你的代码修改如下:
  1. import requests
  2. from bs4 import BeautifulSoup
  3. from prettytable import PrettyTable

  4. def gethttpText(url) :   #获取网页数据
  5.     try :
  6.         r = requests.get(url ,timeout = 30)
  7.         r.raise_for_status()
  8.         r.encoding = r.apparent_encoding
  9.         return r.text
  10.     except :
  11.         print("Funation getHttpText 代码出错!")

  12. def parserPage(itl,html):   #解析网页数据
  13.     try :
  14.         soup = BeautifulSoup(html,"html.parser")
  15.         find_shuju = soup.find('div', attrs={'class': "subjectbox"})  #查找标签div 内容为class="tit_replay"  这是 最新的回复
  16.         find_a = find_shuju.find_all('a')      #进一步查找到 标签  a 内容
  17.         for each in find_a :                   #迭代标签 a  的取内容
  18.             tip_soup = BeautifulSoup(each['tip'],"html.parser")
  19.             ls_name = tip_soup.find('strong').text
  20.             zz_name = tip_soup.find('br').next_element.split(':')[1].split('(')[0]
  21.             itl.append([ls_name,zz_name,each.get("href")])   #放进itl 参数列表中
  22.     except:
  23.         print("Funation parserPage 程序出错!")


  24. def main():
  25.     try:
  26.         url = 'http://bbs.lwhfishing.com/forum.php'
  27.         html = gethttpText(url)
  28.         itl = []
  29.         parserPage(itl,html)
  30.         table = PrettyTable(field_names=("序号","题目","作者","链接"))
  31.         for i,j in enumerate(itl):
  32.             table.add_row([i] + j)
  33.         print(table)
  34.     except :
  35.         print("Funation main 程序出错!")

  36. if __name__ =="__main__" :
  37.     main()
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-3 05:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表