tangshi_poem.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import requests
  2. import os
  3. import json
  4. from lxml import etree
  5. headers = {
  6. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
  7. 'Chrome/104.0.0.0 Safari/537.36'
  8. }
  9. domain = 'https://so.gushiwen.cn'
  10. final_result = []
  11. def get_detail_href(url):
  12. # 获取每首诗的href值
  13. res = requests.get(url)
  14. et = etree.HTML(res.text)
  15. hrefs = et.xpath('//*[@id="html"]/body/div[2]/div[1]/div[2]//span/a/@href')
  16. # 处理href,需要添加域名
  17. new_hrefs = []
  18. for href in hrefs:
  19. new_hrefs.append(domain + href)
  20. return new_hrefs
  21. def get_poem_detail(href):
  22. # 访问每一个详情页,拿到数据
  23. aspx_file_name = href.split("_")[1].split('.')[0]
  24. response_text = requests.get(url=href, headers=headers, timeout=15).text
  25. tree = etree.HTML(response_text)
  26. result = {}
  27. title = tree.xpath('//*[@id="sonsyuanwen"]/div[1]/h1/text()')
  28. result["title"] = "".join(title).strip()
  29. author = tree.xpath('//*[@id="sonsyuanwen"]/div[1]/p/a/text()')
  30. result["author"] = "".join(author).strip()
  31. content = tree.xpath(f'//*[@id="contson{aspx_file_name}"]/text()')
  32. content = "\n".join(content)
  33. result["content"] = "".join(content).strip()
  34. author_info = ''
  35. result["author_info"] = "".join(author_info).strip()
  36. comment = tree.xpath('//*[@id="html"]/body/div[2]/div[1]/div[3]/div[1]/p[2]/text()')
  37. if '注释' in comment:
  38. result["comment"] = "".append(comment.remove('注释')).strip()
  39. else:
  40. result["comment"] = "".join(comment).strip()
  41. translation = tree.xpath('//*[@id="html"]/body/div[2]/div[1]/div[3]/div[1]/p[1]/text()')
  42. if '译文' in translation:
  43. result["translation"] = "".join(translation.remove('译文')).strip()
  44. else:
  45. result["translation"] = "".join(translation).strip()
  46. appreciation = ''
  47. result["appreciation"] = "".join(appreciation).strip()
  48. extention = ''
  49. result["extention"] = "".join(extention).strip()
  50. reading = ''
  51. result["reading"] = "".join(reading).strip()
  52. final_result.append(result)
  53. def main():
  54. url = 'https://so.gushiwen.cn/gushi/tangshi.aspx'
  55. hrefs = get_detail_href(url)
  56. for href in hrefs:
  57. # 访问每一个详情页,得到每个详情页的内容
  58. get_poem_detail(href)
  59. filename = "tangshi/"+".json"
  60. with open(filename, "w", encoding='utf-8') as file:
  61. file.write(json.dumps(final_result, indent=2, ensure_ascii=False))
  62. if __name__ == '__main__':
  63. main()