【问题标题】:urllib2 and BeautifulSoup - loop through urls and return whether html contains "<form" tagurllib2 和 BeautifulSoup - 遍历 url 并返回 html 是否包含“<form”标签
【发布时间】:2016-03-19 17:00:25
【问题描述】:

我是 Python 新手,对 BeautifulSoup 和 urllib 没有经验

我尝试将我自己的代码从其他问题中提取出来,但无济于事,因此我将尝试从下面的伪代码和描述中详细说明我想要实现的目标:

import urllib2
from bs4 import BeautifulSoup
for eachurl in "urllist.txt":
    urllib read first (or 2nd or 3rd) url in list
    find.all("<form")
    if number of "<form" > 0:
        result = True
    if number of "<form" == 0:
        result = False

write result to csv/excel/html

table col 1 = url in urllist
table col 2 = result

所以基本上,我有一个包含 URL 列表的 txt 文件;我希望 urllib 一个一个打开每个 URL,看看 html 是否包含表单标签。 (写入新文件)左侧列中的 URL 字符串和右侧的 yn,取决于查找所有表单标记是否返回大于 0 的结果,然后当然一旦 URL 有就停止txt文件中已经用尽了。

【问题讨论】:

  • 那么具体的问题是什么?您的代码的第一部分是否有效? SO 不是编码服务,因此请说明您的问题。
  • 您需要阅读有关打开和读取文件、使用 urllib 获取资源、使用 BS 和编写 csv 文件的内容。每个都有大量的文档和教程。我建议您找到它们并阅读它们以了解它们是如何工作的。 SO 是关于帮助解决特定问题,而不是为您编写代码。

标签: python html beautifulsoup urllib2


【解决方案1】:

使用requests 而不是urllib2

试试这个:

import requests
from bs4 import BeautifulSoup

with open('data.txt', 'r') as data:
    for line in data:
        res = requests.get(line.strip()).content
        soup = BeautifulSoup(res, 'html.parser')
        with open('result.txt', 'a') as result_file:
            if soup.find_all('form'):
                result_file.write('{} y\n'.format(line.strip()))
            else:
                result_file.write('{} n\n'.format(line.strip()))

数据.txt

http://stackoverflow.com/questions/34263219/urllib2-and-beautifulsoup-loop-through-urls-and-return-whether-html-contains
http://blank.org/

结果.txt

http://stackoverflow.com/questions/34263219/urllib2-and-beautifulsoup-loop-through-urls-and-return-whether-html-contains y
http://blank.org/ n

【讨论】:

    猜你喜欢
    • 2014-05-16
    • 1970-01-01
    • 2017-11-27
    • 2018-10-22
    • 1970-01-01
    • 2020-10-03
    • 2023-03-17
    • 2019-06-24
    • 1970-01-01
    相关资源
    最近更新 更多