Python中文
首页
教程
问答
标签
搜索
登录
注册
如何将输出转储到txt?
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我想做一个简单的程序,从一个网站提取网址,然后将它们转储到一个.txt文件。你知道吗</p> <p>下面的代码运行得很好,但当我试图将其转储到文件时,会出现错误。你知道吗</p> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup, SoupStrainer import requests url = "https://stackoverflow.com" page = requests.get(url) data = page.text soup = BeautifulSoup(data) cr='C:\Users\Admin\Desktop\extracted.txt' for link in soup.find_all('a'): print(link.get('href')) </code></pre> <p>我试过了</p> <pre><code>open(cr, 'w') as f: for link in soup.find_all('a'): print(link.get('href')) f.write(link.get('href')) </code></pre> <p>它转储一些链接,而不是所有链接——它们都在一行中(我得到TypeError:应该是字符串或其他字符缓冲区对象)</p> <p><code>.txt</code>中的结果应该如下所示:</p> <pre><code>/teams/customers /teams/use-cases /questions /teams /enterprise https://www.stackoverflowbusiness.com/talent https://www.stackoverflowbusiness.com/advertising https://stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fstackoverflow.com%2f https://stackoverflow.com/users/signup?ssrc=head&returnurl=%2fusers%2fstory%2fcurrent https://stackoverflow.com https://stackoverflow.com https://stackoverflow.com/help https://chat.stackoverflow.com https://meta.stackoverflow.com https://stackoverflow.com/users/signup?ssrc=site_switcher&returnurl=%2fusers%2fstory%2fcurrent https://stackoverflow.com/users/login?ssrc=site_switcher&returnurl=https%3a%2f%2fstackoverflow.com%2f https://stackexchange.com/sites https://stackoverflow.blog https://stackoverflow.com/legal/cookie-policy https://stackoverflow.com/legal/privacy-policy https://stackoverflow.com/legal/terms-of-service/public </code></pre> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup, SoupStrainer import requests url = "https://stackoverflow.com" page = requests.get(url) data = page.text soup = BeautifulSoup(data) cr='C:\Users\Admin\Desktop\crawler\extracted.txt' with open(cr, 'w') as f: for link in soup.find_all('a'): print(link.get('href')) f.write(link.get('href')) </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>试试这个:</p> <pre><code>with open(cr, 'w') as f: for link in soup.find_all('a'): link_text = link.get('href') if link_text is not None: print(link.get('href')) f.write(link.get('href') + '\n') </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
Python中两个字典的交集
3 回答
python中两个字符串上的异或操作数?
5 回答
Python中两个字符串中的类似句子
10 回答
Python中两个字符串之间的Hamming距离
10 回答
python中两个字符串之间的匹配模式
9 回答
python中两个字符串之间的按位或
3 回答
python中两个字符串之间的数据(字节)切片
7 回答
python中两个字符串之间的模式
9 回答
python中两个字符串作为子字符串的区别
8 回答
Python中两个字符串元组的比较
8 回答
Python中两个字符串列表中的公共字符串
6 回答
python中两个字符串的Anagram测试
10 回答
Python中两个字符串的正则匹配
10 回答
python中两个字符串的笛卡尔乘积
4 回答
Python中两个字符串相似性的比较
1 回答
python中两个字符串语义相似度的求法
5 回答
Python中两个字符置换成固定长度的字符串,每个字符的数目相等
6 回答
Python中两个对数方程之间的插值和平滑数据
2 回答
Python中两个对象之间的And/Or运算符
4 回答
python中两个嵌套字典中相似键的和值
10 回答