# 求助python批量提取网页部分内容合并出现问题

**URL:** <https://forum.freemdict.com/t/topic/22422>\
**Category:** 技术交流与词典编修\
**Created:** [2023 年7 月 30 日 03:15 UTC](https://forum.freemdict.com/t/topic/22422 "2023-07-30T03:15:01Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

作者： ![xmg123](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/x/7cd45c/32.png) [@xmg123](https://forum.freemdict.com/u/xmg123)\
发布日期： [2023 年7 月 30 日 03:15 UTC](https://forum.freemdict.com/t/topic/22422/1 "2023-07-30T03:15:01Z")

</div>

下载的网页用python提取部分内容，然后批量合并，出现合并的条目与实际的文件数量相比少了很多，中间也没报错，实际文件数量十万多，只合并了三万多，不知道咋回事，

```auto
import re
import pandas as pd
import os
import random
import requests
from lxml import etree
import sys
import subprocess
import copy
import chardet
import urllib.parse
from tidylib import tidy_document

w_path = "F:/1"
w_files = os.listdir(w_path)
# print(w_files)
for w_file in w_files:
    f1 = open(w_path+"/"+str(w_file), encoding="utf-8")
    print(f1)
    w_txt=f1.read()
    obj = re.compile(r'<title>(?P<bi>.*?) - 维基百科，自由的百科全书</title>.*?'
                     r'<div class="pre-content heading-holder">(?P<h1>.*?)<nav class="page-actions-menu">.*?'
                     r'<div id="mw-content-subtitle" lang="zh-Hans-CN" dir="ltr">(?P<neirong>.*?)<div class="post-content footer-content">', re.S)
    resu = obj.finditer(w_txt)
    f = open("F:/ceshi/weiji1.txt",'a',encoding='utf-8')
    for it in resu:
        # print(it.group("title"))
        biaoti = it.group("bi")
        name = it.group("h1")
        neirong = it.group("neirong")
        # # dic = it.groupdict()
        # print(name)
        # print(biaoti)
        f.write(f'{biaoti}\n{name}\n{neirong}\n</>\n')
        print('正在打印')
    f.close()
    print('完成')

```

---

<div class="post-metadata">

作者： ![last\_idol](https://forumcdn.freemdict.com/user_avatar/forum.freemdict.com/last_idol/32/2205_2.png) [@last\_idol](https://forum.freemdict.com/u/last_idol)\
发布日期： [2023 年7 月 30 日 03:21 UTC](https://forum.freemdict.com/t/topic/22422/2 "2023-07-30T03:21:23Z")

</div>

没出错就是正则匹配的少了，建议用beautiful soup提取内容。

[https://beautifulsoup.readthedocs.io/zh\_CN/v4.4.0/#id8](https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/#id8)

---

<div class="post-metadata">

作者： ![xmg123](https://forumcdn.freemdict.com/letter_avatar_proxy/v4/letter/x/7cd45c/32.png) [@xmg123](https://forum.freemdict.com/u/xmg123)\
发布日期： [2023 年7 月 30 日 03:49 UTC](https://forum.freemdict.com/t/topic/22422/3 "2023-07-30T03:49:27Z")

</div>

网页布局很多都这样，就是提取画红线之间的，正则直接.\*？省事些。

 ![](https://forumcdn.freemdict.com/uploads/default/original/3X/d/9/d9fa607428c6304450de556ece734fe3d4c64580.jpeg)

---

<div class="post-metadata">

作者： ![last\_idol](https://forumcdn.freemdict.com/user_avatar/forum.freemdict.com/last_idol/32/2205_2.png) [@last\_idol](https://forum.freemdict.com/u/last_idol)\
发布日期： [2023 年7 月 30 日 03:55 UTC](https://forum.freemdict.com/t/topic/22422/4 "2023-07-30T03:55:39Z")

</div>

没提取到内容的文本，打印下文件名，看看是不是正则的问题。
