【问题标题】:can't fetch the data using beautiful soup无法使用漂亮的汤获取数据
【发布时间】:2015-08-21 14:27:06
【问题描述】:

我正在尝试使用 Beautiful Soup 编写简单的脚本,它可以只删除两个信息并从网站生成一个 SQL 文件。

import mechanize
import urlparse
from bs4 import BeautifulSoup

op = mechanize.Browser()
op.open("https://www.mentalhelp.net/symptoms/")
for link in op.links():
print link.text
print urlparse.urljoin(link.base_url, link.url)
get = BeautifulSoup(urllib2.urlopen("https://www.mentalhelp.net/symptoms/").read()).findAll('p')
print get
print "\n"

错误:

C:\Python27>python symtoms.py 文件“symtoms.py”,第 8 行 打印链接.文本 ^ IndentationError: 需要一个缩进块

我只想要一个脚本,它会废弃这些项目和简短描述并生成一个只有两个字段“name”和“sug”的 SQL 文件。 “name”是那些项目,“sug”是那些描述。

【问题讨论】:

    标签: python web-scraping beautifulsoup web-crawler mechanize


    【解决方案1】:

    缩进在 Python 中很重要,它用于确定块,例如 for 循环或 if 块或 while 循环或函数等。

    在您提供的代码中,for 循环后的语句在 for 循环内的缩进不正确,并且 for 循环在其主体中至少需要一个语句,我认为您希望 for 循环下面的行在里面for 循环,所以你应该在 for 循环中缩进它们。

    代码-

    for link in op.links():
        print link.text
        print urlparse.urljoin(link.base_url, link.url)
        get = BeautifulSoup(urllib2.urlopen("https://www.mentalhelp.net/symptoms/").read()).findAll('p')
        print get
        print "\n"
    

    虽然我不确定这是否会得到你想要的,但它会修复你当前的错误。


    对于获取 classic symptoms 及其描述的新要求,您可以使用 -

    soup = BeautifulSoup(urllib2.urlopen("https://www.mentalhelp.net/symptoms/").read())
    for div in soup.findAll('div',{'id':'page'}):
        for entrydiv in div.findAll('div',{'class':'h4 entry-title'}):
            print(entrydiv.get_text())
            print(entrydiv.next_sibling.get_text())
    

    【讨论】:

    • 谢谢你!代码至少现在可以工作。是的,它不适合我的目的。我只需要获取症状列表下的症状名称和描述。但它显示了很多。我是python的菜鸟。还做不到。你能帮忙吗?
    • 您能否使用页面的 html 以及您想要的确切信息更新问题?另外,如果答案有帮助,我想请您通过单击左侧的勾号来接受答案,这将对社区有所帮助。
    • 我很乐意为您提供帮助。
    • 很高兴你为我努力。
    • 我只需要症状名称及其描述。描述可以是完整的或部分的,没问题。我只是想看看它实际上是如何工作的。
    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 2019-05-08
    相关资源
    最近更新 更多