Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: a bytes-like object is required, not 'dict'

#coding:utf-8
import requests
from bs4 import BeautifulSoup

url = 'http://news.qq.com/'
wbdata = requests.get(url).text
soup = BeautifulSoup(wbdata,'lxml')
news_title = soup.select("div.text > em.f14 > a.linkto")

for n in news_title:
    title = n.get_text()
    link = n.get("href")
    data = {"标题":title,"链接":link}
    print(data)
    f = open('news.txt','wb')
    f.write(data)
    f.close()

enter image description here

Here are codes. So when I run it,it gives"TypeError: a bytes-like object is required, not 'dict'",I tried many solutions,no help. Can someone help me? thx!

like image 863
zhangslob Avatar asked May 03 '26 06:05

zhangslob


1 Answers

f.write(data)

This is where the problem is. You are passing in a dictionary instead of a byte like object. For example when I change your code to the following:

#coding:utf-8
import requests
from bs4 import BeautifulSoup

url = 'http://news.qq.com/'
wbdata = requests.get(url).text
soup = BeautifulSoup(wbdata,'lxml')
news_title = soup.select("div.text > em.f14 > a.linkto")

for n in news_title:
    title = n.get_text()
    link = n.get("href")
    data = {"k":title,"a":link}
    print(data)
    f = open('news.txt','wb')
    data = b'123'
    f.write(data)
    f.close()

... I get the following:

{'k': '辽宁舰将绕台一周“武吓”蔡英文?外交部回应', 'a': 'http://news.qq.com/a/20170104/031454.htm'} ...

Which I assume is what you want.

Alternatively change the line:

f = open('news.txt', 'wb') 

to

f = open('news.txt', 'w')

and that way you can write in str rather than a byte-like object. In any case you shouldn't be passing in a dict.

like image 185
chumbaloo Avatar answered May 04 '26 20:05

chumbaloo