【问题标题】:Extract text between two text strings from webpage with BeautifulSoup and Python使用 BeautifulSoup 和 Python 从网页中提取两个文本字符串之间的文本
【发布时间】:2016-04-28 10:55:34
【问题描述】:

BeautifulSoup 上有很多内容,但我找不到任何答案...我想通过在代码中指定前后的文本位来提取 html 的两位之间的文本。我可以用 Outwit Python 模块做到这一点,但这次需要使用 BeautifulSoup...

我想要的页面是下面的用户名:

<a class="generic_class" href="/people/username">

所以,我想指定beautifulsoup 通过告诉它查找来抓取用户名

'a class="generic_class" href="/people/'

前位刮后停

'"'

然后我希望它在来自 csv 的 url 循环中执行此操作(这已经有效),然后将结果逐行附加到新的 csv(此位可能不起作用):

for row in url_reader:
    url = row[0]
    page = br.open(url).read()
    soup = BeautifulSoup(br.response().read())
    user = soup.findAll('<a class="generic_class" href="/people/') # this is the line where the code that works should go! Obviously this bit does nothing as it doesn't extract what comes after, stopping at the closing quotation mark for the end of the href.
    page.append.user(output_file) # not sure if this is right?!

显然,在理想情况下,我会将其放在 if/else to if(查找“未找到页面”)和 else(执行上述操作)中以处理不起作用的 url,但我一旦我可以真正使事情正常工作,就会进行错误处理!这是我现在的首要任务...

非常感谢任何帮助。

【问题讨论】:

    标签: python python-2.7 csv web-scraping beautifulsoup


    【解决方案1】:

    你不能只提取“href”属性值并解析它吗?

    usernames = []
    
    for anchor in soup.findAll('a', {'class': 'generic_class'}):
        usernames.append(anchor['href'].split('/')[-1])
    
    with open('usernames.csv', 'ab') as f:
        writer = csv.writer(f)
        for username in usernames:
            writer.writerow([username])
    

    这只是一个简单的例子,我建议做一些额外的验证等。

    【讨论】:

    • 这给了我 AttributeError: 'set' object has no attribute 'items'
    • 不知道你从哪里得到这个错误,我用这个来测试它:html_doc = """ test
      """ 该错误来自哪一行?
    • Traceback 说您建议的答案的第一行 :(
    • for attr, matchAgainst in self.attrs.items(): AttributeError: 'set' object has no attribute 'items'
    • 对不起,我已经更正了我的答案。我打错字并设置而不是字典,不知道为什么但它确实在我的机器上工作:) {'class', 'generic_class'} -> {'class': 'generic_class'}
    【解决方案2】:

    你可以在href属性中传递一个函数:

    def start_with_people(href):
        return href and href.startswith('/people/')
    
    a_tags = soup.find_all('a', class_='generic_class', href=start_with_people)
    

    这将返回所有具有以/people/ 开头的href 的&lt;a&gt; 标签。

    一旦你有了这些锚标签:

    1. 你可以遍历它

    2. 获取href

    3. 拆分后获取用户名

    【讨论】:

    • 这给了我一个错误:a_tags = soup.find_all('a', class_='generic_class', href=start_with_people) TypeError: 'NoneType' object is not callable
    • 如果我把它改成 'soup.findAll' 那么它不会出错,但它也找不到任何东西。
    • 你有哪个版本的?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多