【发布时间】:2017-03-18 12:34:56
【问题描述】:
我正在尝试使用 Stem 项目中的 To Russia With Love 教程通过 TOR 使用 BS4。
我使用 i.a. 稍微重写了代码。 this answer,现在是这个样子,
SOCKS_PORT=7000
def query(url):
output = io.BytesIO()
query = pycurl.Curl()
query.setopt(pycurl.URL, url)
query.setopt(pycurl.PROXY, 'localhost')
query.setopt(pycurl.PROXYPORT, SOCKS_PORT)
query.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5_HOSTNAME)
query.setopt(pycurl.WRITEFUNCTION, output.write)
try:
query.perform()
return output.getvalue()
except pycurl.error as exc:
return "Unable to reach %s (%s)" % (url, exc)
def print_bootstrap_lines(line):
if "Bootstrapped " in line:
print(term.format(line, term.Color.BLUE))
print(term.format("Starting Tor:\n", term.Attr.BOLD))
tor_process = stem.process.launch_tor_with_config(
tor_cmd = '/Applications/TorBrowser.app/Contents/MacOS/Tor/tor.real',
config = {
'SocksPort': str(SOCKS_PORT),
'ExitNodes': '{ru}',
'GeoIPFile': r'/Applications/TorBrowser.app/Contents/Resources/TorBrowser/Tor/geoip',
'GeoIPv6File' : r'/Applications/TorBrowser.app/Contents/Resources/TorBrowser/Tor/geoip6'
},
init_msg_handler = print_bootstrap_lines,
)
print(term.format("\nChecking our endpoint:\n", term.Attr.BOLD))
print(term.format(query("https://www.atagar.com/echo.php"), term.Color.BLUE))
我能够建立 Tor 电路,但在“检查我们的端点”时,我收到以下错误,
Checking our endpoint:
Traceback (most recent call last):
File "<ipython-input-804-68f8df2c050b>", line 40, in <module>
print(term.format(query('https://www.atagar.com/echo.php'), term.Color.BLUE))
File "/Applications/anaconda/lib/python3.6/site-packages/stem/util/term.py", line 139, in format
if RESET in msg:
TypeError: a bytes-like object is required, not 'str'
我应该改变什么才能看到端点?
我已经通过将上面代码的最后一行更改为,暂时解决了这个问题,
test=requests.get('https://www.atagar.com/echo.php')
soup = BeautifulSoup(test.content, 'html.parser')
print(soup)
但我想知道如何让“原始”线路正常工作。
【问题讨论】:
-
你可能想发布你的代码,否则别人帮不了你!当它想要一个类似字节的对象时,看起来你给它一个字符串,你可以转换例如通过使用
b。 This SO 帖子可能会有所帮助。 -
@patrick。我添加了代码。
-
您是否尝试将此处的
url变量:query.setopt(pycurl.URL, url)更改为字节字符串?请参阅input handling 上的此处:在 Python 3 下,由于 PycURL 使用 bytes 参数调用 write 回调,因此必须将响应写入 BytesIO 对象;还有一个模板可以复制 -
将您的回报更改为
return output.getvalue().decode("utf-8")应该可以解决它。请注意,您可能需要将 utf-8 更改为另一种编码,但我会先尝试。
标签: python web-scraping tor bs4