“在尝试解析电子邮件的html时不能在像对象这样的字节上使用字符串模式

问题描述 投票:1回答:1

因此,我有一个正在使用了几天的脚本,试图从我拥有的csv中获取电子邮件列表,但是现在我遇到了这个障碍。这是代码:

import sys
try:
    import urllib.request as urllib2
except ImportError:
    import urllib2
import re
import csv

list1 = []
list2 = []
list3 = []

def addList():
    with open('file.csv', 'rt') as f:
        reader = csv.reader(f)
        for row in reader:
            for s in row:
                list2.append(s)

def getAddress(url):
    http = "http://"
    https = "https://"

    if http in url:
        return url
    elif https in url:
        return url
    else:
        url = "http://" + url
        return url

def parseAddress(url):
    global list3
    try:
      website = urllib2.urlopen(getAddress(url))
      html = website.read()

      addys = re.findall('''[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?''', html, flags=re.IGNORECASE)

      global list1
      list1.append(addys)

    except urllib2.HTTPError as err:
        print ("Cannot retrieve URL: HTTP Error Code: "), err.code
        list3.append(url)
    except urllib2.URLError as err:
        print ("Cannot retrive URL: ") + err.reason[1]
        list3.append(url)

def execute():
    global list2
    addList()
    totalNum = len(list2)
    atNum = 1
    for s in list2:
        parseAddress(s)
        print ("Processing ") + str(atNum) + (" out of ") + str(totalNum)
        atNum = atNum + 1

    print ("Completed. Emails parsed: ") + str(len(list1)) + "."


### MAIN

def main():
    global list2
    execute()
    global list1
    myFile = open("finishedFile.csv", "w+")
    wr = csv.writer(myFile, quoting=csv.QUOTE_ALL)
    for s in list1:
        wr.writerow(s)
    myFile.close
    global list3
    failFile = open("failedSites.csv", "w+")
    write = csv.writer(failFile, quoting=csv.QUOTE_ALL)
    for j in list3:
        write.writerow(j)
    failFile.close

main()

当我运行它时,出现此错误:

    Traceback (most recent call last):
  File "pagescanner.py", line 85, in <module>
    main()
  File "pagescanner.py", line 71, in main
    execute()
  File "pagescanner.py", line 60, in execute
    parseAddress(s)
  File "pagescanner.py", line 42, in parseAddress
    addys = re.findall('''[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?''', html, flags=re.IGNORECASE)
  File "/usr/lib/python3.5/re.py", line 213, in findall
    return _compile(pattern, flags).findall(string)
TypeError: cannot use a string pattern on a bytes-like object

所以我发现我需要弄清楚如何将html字符串编码为字节以进行编码,下面泰勒的回答帮助我做到了,但是现在我得到了这个错误:

Traceback (most recent call last):
  File "/usr/lib/python3.5/urllib/request.py", line 1254, in do_open
    h.request(req.get_method(), req.selector, req.data, headers)
  File "/usr/lib/python3.5/http/client.py", line 1107, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python3.5/http/client.py", line 1152, in _send_request
    self.endheaders(body)
  File "/usr/lib/python3.5/http/client.py", line 1103, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python3.5/http/client.py", line 934, in _send_output
    self.send(msg)
  File "/usr/lib/python3.5/http/client.py", line 877, in send
    self.connect()
  File "/usr/lib/python3.5/http/client.py", line 849, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/usr/lib/python3.5/socket.py", line 712, in create_connection
    raise err
  File "/usr/lib/python3.5/socket.py", line 703, in create_connection
    sock.connect(sa)
OSError: [Errno 22] Invalid argument

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "pagescanner.py", line 39, in parseAddress
    website = urllib2.urlopen(getAddress(url))
  File "/usr/lib/python3.5/urllib/request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.5/urllib/request.py", line 466, in open
    response = self._open(req, data)
  File "/usr/lib/python3.5/urllib/request.py", line 484, in _open
    '_open', req)
  File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.5/urllib/request.py", line 1282, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "/usr/lib/python3.5/urllib/request.py", line 1256, in do_open
    raise URLError(err)
urllib.error.URLError: <urlopen error [Errno 22] Invalid argument>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "pagescanner.py", line 85, in <module>
    main()
  File "pagescanner.py", line 71, in main
    execute()
  File "pagescanner.py", line 60, in execute
    parseAddress(s)
  File "pagescanner.py", line 51, in parseAddress
    print ("Cannot retrive URL: ") + err.reason[1]
TypeError: 'OSError' object is not subscriptable

这是否意味着列表中的一个网址不是有效的网址?我以为我终于从csv文件中删除了所有错误网址,但我可能需要再看一遍

python python-3.x string byte encode
1个回答
0
投票

要回答您的问题,您只需要正确解码响应即可。代替html = website.read()尝试html = website.read().decode('utf-8')

请参见Convert bytes to a string

我还将推荐一些可能会使您的生活更轻松的事情。urllib.parse使处理URL的麻烦减轻了很多,当您不可避免地在某个地方遇到bug时,往往会使事情更具可读性。

https://docs.python.org/3.5/library/urllib.parse.html

requests库几乎也是处理HTTP请求的黄金标准,可能有助于解决标准urllib.request带来的编码和其他开销方面的一些混乱。

https://requests.readthedocs.io/en/master/

[beautifulsoup是处理HTML的绝佳工具。

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#

© www.soinside.com 2019 - 2024. All rights reserved.