【问题标题】:Webscrape Multiple Pages with python - output issue使用 python 抓取多个页面 - 输出问题
【发布时间】:2019-06-04 08:29:14
【问题描述】:

python 社区新年快乐,

我正在尝试使用 Python Beautifulsoup4 从网站中提取表格

我很难在输出文件中查看结果。 代码运行顺利,但没有写入文件。

下面是我的代码

from bs4 import BeautifulSoup as bsoup
import requests as rq
import re

base_url = 'http://www.creationdentreprise.sn/rechercher-une-societe?field_rc_societe_value=&field_ninea_societe_value=&denomination=&field_localite_nid=All&field_siege_societe_value=&field_forme_juriduqe_nid=All&field_secteur_nid=All&field_date_crea_societe_value='
r = rq.get(base_url)

soup = bsoup(r.text)
# Use regex to isolate only the links of the page numbers, the one you click on.
page_count_links = soup.find_all("a",href=re.compile(r".http://www.creationdentreprise.sn/rechercher-une-societe?field_rc_societe_value=&field_ninea_societe_value=&denomination=&field_localite_nid=All&field_siege_societe_value=&field_forme_juriduqe_nid=All&field_secteur_nid=All&field_date_crea_societe_value=&page=.*"))
try: # Make sure there are more than one page, otherwise, set to 1.
    num_pages = int(page_count_links[-1].get_text())
except IndexError:
    num_pages = 1

# Add 1 because Python range.
url_list = ["{}&page={}".format(base_url, str(page)) for page in range(1, 3)]

# Open the text file. Use with to save self from grief.
with open("results.txt","wb") as acct:
    for url_ in url_list:
        print("Processing {}...".format(url_))
        r_new = rq.get(url_)
        soup_new = bsoup(r_new.text)
        for tr in soup_new.find_all('tr', align='center'):
            stack = []
            for td in tr.findAll('td'):
                stack.append(td.text.replace('\n', '').replace('\t', '').strip())
            acct.write(", ".join(stack) + '\n')

【问题讨论】:

  • 你在except IndexError:之后缺少缩进
  • 其实语句是num_pages = 1,我复制代码时出错了
  • 你看到了。很快将我的评论更改为缺少缩进。但仍然通过代码工作,你是对的,没有得到输出
  • 我收到 404 响应,因为找不到您用作 url_ 的页面。检查你那里没有错字或其他东西
  • 更新url,现在应该可以了

标签: python loops web-scraping beautifulsoup python-beautifultable


【解决方案1】:

soup_new.find_all('tr', align='center') 返回一个空列表

尝试将其切换为for tr in soup_new.find_all('tr'):

其次,由于您使用的是字符串,请将模式 with open("results.txt","wb") 切换为 with open("results.txt","w")

from bs4 import BeautifulSoup as bsoup
import requests as rq
import re

base_url = 'http://www.creationdentreprise.sn/rechercher-une-societe?field_rc_societe_value=&field_ninea_societe_value=&denomination=&field_localite_nid=All&field_siege_societe_value=&field_forme_juriduqe_nid=All&field_secteur_nid=All&field_date_crea_societe_value=&page=2'
r = rq.get(base_url)

soup = bsoup(r.text)
# Use regex to isolate only the links of the page numbers, the one you click on.
page_count_links = soup.find_all("a",href=re.compile(r".http://www.creationdentreprise.sn/rechercher-une-societe?field_rc_societe_value=&field_ninea_societe_value=&denomination=&field_localite_nid=All&field_siege_societe_value=&field_forme_juriduqe_nid=All&field_secteur_nid=All&field_date_crea_societe_value=&page=.*"))
try: # Make sure there are more than one page, otherwise, set to 1.
    num_pages = int(page_count_links[-1].get_text())
except IndexError:
    num_pages = 1

# Add 1 because Python range.
url_list = ["{}&page={}".format(base_url, str(page)) for page in range(1, 3)]

# Open the text file. Use with to save self from grief.
with open("results.txt","w") as acct:
    for url_ in url_list:

        #url_ = url_list[0]

        print("Processing {}...".format(url_))
        r_new = rq.get(url_)
        soup_new = bsoup(r_new.text)


        for tr in soup_new.find_all('tr'):
            stack = []
            for td in tr.findAll('td'):
                stack.append(td.text.replace('\n', '').replace('\t', '').strip())
            acct.write(", ".join(stack) + '\n')

【讨论】:

  • 刚刚编辑了网址但仍未写入数据...我认为正如您提到的问题是 soup_new.find_all('tr', align='center') 但仍然不知道如何解决这个
  • 是的,找到了。检查上面的答案。为我工作。写入文件
  • 你在代码中做了什么改变?仍然没有为我写信
  • for tr in soup_new.find_all('tr'):with open("results.txt","w"):
  • 另外,with open("results.txt","w"): 会将文件保存在当前工作目录下。我喜欢指定文件,所以我不会感到惊讶/四处寻找它。所以你可以明确地包含你想要的文件夹的路径。但它适用于我。你遇到了什么错误?
猜你喜欢
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 2018-07-28
  • 2017-11-17
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多