I have a code as below.
I run this code using python 3.7
idle, which runs successfully. But when I save it as file.py
and run it from using cmd, it pops import module
error.
My code:
JavaScript
x
20
20
1
import requests
2
from lxml import html
3
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'}
4
# url to scrape data from
5
link = 'https://www.bhaskar.com/sports/'
6
7
# path to particular element
8
path = '//*[@id="top-nav1"]'
9
10
response = requests.get(link,headers)
11
byte_string = response.content
12
13
# get filtered source code
14
source_code = html.fromstring(byte_string)
15
print(source_code)
16
# jump to preferred html element
17
tree = source_code.xpath(path)
18
print(tree.text_content())
19
20
Error : cannot import name ‘html’ from ‘lxml’
I can not understand when both are running on the same python files why such Error pop!!!
Advertisement
Answer
You’re confusing Python’s import machinery by having named your script lxml.py
, the same name as the lxml
package you’re importing.
Rename it to, say lxml_test_thing.py
and it’ll work.